使用Java實現(xiàn)遠(yuǎn)程文件下載到本地目錄
前言
今天開發(fā)時遇見了一個下載附件的需求,他的附件是存在一個網(wǎng)盤里查詢時只是給我返回了一個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>備注:遠(yuǎn)程文件下載到本地 方法二選一<p>
*/
public class downloadUtil {
/**
* 下載遠(yuǎn)程文件并保存到本地
*
* @param remoteFilePath-遠(yuǎn)程文件路徑
* @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();
}
}
}
/**
* 下載遠(yuǎn)程文件并保存到本地
*
* @param remoteFilePath-遠(yuǎn)程文件路徑
* @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) {
/*遠(yuǎn)程文件路徑*/
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);
}
}
二、測試介紹
這里我使用的是網(wǎng)上搜索的圖片路徑做了一下測試僅供參考 如正文介紹文章來源:http://www.zghlxwxcb.cn/news/detail-519746.html
總結(jié)
使用Java實現(xiàn)遠(yuǎn)程文件下載到本地目錄記錄就到此結(jié)束了文章來源地址http://www.zghlxwxcb.cn/news/detail-519746.html
到了這里,關(guān)于使用Java實現(xiàn)遠(yuǎn)程文件下載到本地目錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!