最近有个项目需要通过文件链接下载文件到本地 所以我写了个小demo去实现通过文件链接下载到本地文件夹里

主要运用到了 java的net包和io包

具体实现思路是 通过文件链接来new一个URL对象


ini

体验AI代码助手

代码解读

复制代码

URL url = new URL(urlStr);

然后再通过url对象去打开一个http连接去创建一个HttpURLConnection实例


ini

体验AI代码助手

代码解读

复制代码

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

然后可以对这个HttpURLConnection进行设置超时响应和设置链接响应参数等 然后得到一个文件的输入流


java

体验AI代码助手

代码解读

复制代码

//设置超时间为3秒 conn.setConnectTimeout(3 * 1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 InputStream inputStream = conn.getInputStream();

然后通过一个读取输入流的方法给转换成我们需要的文件字节数组 具体方法为创建一个为1024的字节数组 然后创建一个内存操作流对象做为缓冲区来对输入流去进行一个操作去把输入流给转化成字节数组


less

体验AI代码助手

代码解读

复制代码

* 从输入流中获取字节数组 * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); }

然后再通过想要存储的文件路径去new一个文件目录出来 然后再创建一个FileOutputStream对象 去把得到的字节数组给写入到文件里 这样就完成了一个下载的过程。

具体详细代码如下 读者可自取


ini

体验AI代码助手

代码解读

复制代码

public static String downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置超时间为3秒 conn.setConnectTimeout(3 * 1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 InputStream inputStream = conn.getInputStream(); //获取自己数组 byte[] getData = readInputStream(inputStream); //文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdir(); } File file = new File(saveDir + File.separator + fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } String fileinfo = file.getAbsolutePath(); System.out.println(fileinfo + " download success"); return fileinfo; } /** * 从输入流中获取字节数组 * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); }

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐