public void downloadFile(String downloadURL,String localFilePath,String zipName) throws IOException {
BufferedInputStream in = null;
BufferedOutputStream out = null;
HttpURLConnection httpUrl = null;
// String localFilePath = "D:/aaa/";
// String zipName="file.zip";
try {
// 定义要进行远程下载的路径
URL url = new URL(downloadURL);
httpUrl = (HttpURLConnection) url.openConnection();
File file = new File(localFilePath);
if(!file.exists()){
file.mkdirs();
}
// 开启文件下载路径的连接
httpUrl.connect();
// 开启输入流
in = new BufferedInputStream(httpUrl.getInputStream());
// 将获取到的文件输出到输出流当中
out = new BufferedOutputStream(new FileOutputStream(localFilePath + zipName));
// 定义远程下载的文件最大为2MB
int len = 2048;
byte[] bytes = new byte[len];
// 将输出流写到本地目录中
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
// 将流关闭
out.close();
in.close();
httpUrl.disconnect();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 将流对象关闭
out.close();
in.close();
httpUrl.disconnect();
}
}
URL从远程服务器下载文件到本地
最新推荐文章于 2024-10-08 07:28:50 发布