Java如何实现远程文件下载到本地目录,
分享于 点击 47041 次 点评:120
Java如何实现远程文件下载到本地目录,
目录
- 前言
- 一、正文介绍
- 二、测试介绍
- 总结
前言
今天开发时遇见了一个下载附件的需求
他的附件是存在一个网盘里查询时只是给我返回了一个https的路径
需要通过这个路径把附件下载到本地的目录里
一、正文介绍
import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; /** * @Author * @Date * @Version 1.0 * <p>备注:远程文件下载到本地 方法二选一<p> */ public class downloadUtil { /** * 下载远程文件并保存到本地 * * @param remoteFilePath-远程文件路径 * @param localFilePath-本地文件路径(带文件名) */ 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(); } } } /** * 下载远程文件并保存到本地 * * @param remoteFilePath-远程文件路径 * @param localFilePath-本地文件路径(带文件名) */ 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(); } } } } /** * 小试牛刀 * @param args */ 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实现远程文件下载到本地目录记录就到此结束了
以上为个人经验,希望能给大家一个参考,也希望大家多多支持3672js教程。
您可能感兴趣的文章:- java获取本地文件和远程文件的方式代码示例
- java 远程文件url如何转为输入流
- java利用SMB读取远程文件的方法
- Java语言实现简单FTP软件 FTP远程文件管理模块实现(10)
- java断点续传功能实例(java获取远程文件)
相关文章
- 暂无相关文章
用户点评