如何通过url文件路径下载到本地
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FilesUtil {
/**
* 通过url读取文件
* @param url 路径
*/
public static byte[] getFileStream(String url){
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
return btImg;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从输入流中获取数据
* @param inStream 输入流
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
/**
* 下载文件到本地
* @param url 文件全路径+文件名
* @param localUrl 下载到本地的路径,例:windows:D://、linux:/home/server/img/
*/
public static String downloadFileToLocal(String url,String localUrl){
// 将网络文件下载本地
try{
byte[] data = FilesUtil.getFileStream(url);
String substring = url.substring(url.lastIndexOf("/") + 1);
String name = localUrl + substring;
//创建一个文件对象
File file = new File(name);
//创建输出流
FileOutputStream outStream = new FileOutputStream(file);
//写入数据
outStream.write(data);
//关闭输出流,释放资源
outStream.close();
return name;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}