前言
今天开发时遇见了一个下载附件的需求
他的附件是存在一个网盘里查询时只是给我返回了一个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实现远程文件下载到本地目录记录就到此结束了
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论