使用Java实现远程文件下载到本地目录 文章目录 使用Java实现远程文件下载到本地目录前言一、正文介绍二、测试介绍总结 前言 今天开发时遇见了一个下载附件的需求,他的附件是存在一个网盘里查询时只是给我返回了一个https的路
今天开发时遇见了一个下载附件的需求,他的附件是存在一个网盘里查询时只是给我返回了一个https的路径,需要通过这个路径把附件下载到本地的目录里
import java.io.*;import java.net.HttpURLConnection;import java.net.URL;import java.NIO.channels.Channels;import java.nio.channels.ReadableByteChannel;public class downloadUtil { public static void downloadFile1(String remoteFilePath, String localFilePath) { URL urlfile = null; HttpURLConnection httpUrl = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; File f = new File(localFilePath); try { urlfile = new URL(remoteFilePath); httpUrl = (HttpURLConnection) urlfile.openConnection(); httpUrl.connect(); bis = new BufferedInputStream(httpUrl.getInputStream()); bos = new BufferedOutputStream(new FileOutputStream(f)); int len = 2048; byte[] b = new byte[len]; while ((len = bis.read(b)) != -1) { bos.write(b, 0, len); } bos.flush(); bis.close(); httpUrl.disconnect(); } catch (Exception e) { e.printStackTrace(); } finally { try { bis.close(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void downloadFile2(String remoteFilePath, String localFilePath) { URL WEBsite = null; ReadableByteChannel rbc = null; FileOutputStream fos = null; try { website = new URL(remoteFilePath); rbc = Channels.newChannel(website.openStream()); fos = new FileOutputStream(localFilePath);//本地要存储的文件地址 例如:test.txt fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (Exception e) { e.printStackTrace(); }finally{ if(fos!=null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(rbc!=null){ try { rbc.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { String remoteFilePath1 = "https://tenfei01.cfp.cn/creative/vcg/800/new/VCG211157640278-VXD.jpg"; String remoteFilePath2 = "https://pic.3gbizhi.com/2019/1112/20191112013312648.jpg"; String localFilePath1 ="E:\\LeStoreDownload\\update\\广州塔.jpg"; String localFilePath2 ="E:\\LeStoreDownload\\update\\大桥.jpg"; downloadFile1(remoteFilePath1,localFilePath1); downloadFile2(remoteFilePath2,localFilePath2); }}
这里我使用的是网上搜索的图片路径做了一下测试仅供参考 如正文介绍
使用Java实现远程文件下载到本地目录记录就到此结束了
来源地址:https://blog.csdn.net/qq_49417441/article/details/129733004
--结束END--
本文标题: 使用Java实现远程文件下载到本地目录
本文链接: https://lsjlt.com/news/373180.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-01
2024-04-03
2024-04-03
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0