有時(shí)候在java網(wǎng)站開(kāi)發(fā)過(guò)程中,經(jīng)常要用到下載遠(yuǎn)程文件到本地,如下載OSS的文件或者圖片到本地服務(wù)器,然后再用郵件發(fā)送。實(shí)現(xiàn)代碼大概如下:
package com.fwwl.fwqy.common.utils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class downloadUtils {
/**
* 下載遠(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);//本地要存儲(chǔ)的文件地址 例如: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();
}
}
}
}
}
但這里會(huì)有個(gè)安全問(wèn)題,比如別人把遠(yuǎn)程的文件改為木馬,那么下載到服務(wù)器就容易對(duì)網(wǎng)站進(jìn)行破壞,所以在下載的過(guò)程中,最好使用內(nèi)部存儲(chǔ)的文件,路徑不要被篡改,然后對(duì)文件的類型進(jìn)行判斷,同時(shí)不要給文件執(zhí)行權(quán)限。
如沒(méi)特殊注明,文章均為方維網(wǎng)絡(luò)原創(chuàng),轉(zhuǎn)載請(qǐng)注明來(lái)自http://pdcharm.com/news/8575.html