版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gelong_bokewang/article/details/88355451
最近工作因为需求要做一个小功能,根据客户给的的网路路径进行文件的下载。
下面不多说直接上代码:
package com.gl;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class testIo {
/**
* 从网络Url中下载文件
* @param urlStr 下载文件路径
* @param fileName 文件名称包含类型
* @param savePath 保存本地的路径
* @throws IOException
*/
public void testIO(String urlStr, String fileName, String savePath) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为5秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//创建保存路径
File saveDir = new File(savePath);
if(!saveDir.exists()) {
saveDir.mkdir();
}
//创建文件
File file = new File(saveDir+File.separator+fileName);
//文件输出流
FileOutputStream fout = new FileOutputStream(file);
//输出文件
byte[] buff = new byte[4096];
int len = -1;
while ((len = inputStream.read(buff)) != -1) {
fout.write(buff,0,len);
}
//关闭输出输入流
fout.close();
inputStream.close();
System.out.println("info:"+url+" download success");
}
}
这里主要使用的就是java.io类。
在这之前网上找到的一些例子如下:
public void testIO(String urlStr, String fileName, String savePath) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为5秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//创建保存路径
File saveDir = new File(savePath);
if(!saveDir.exists()) {
saveDir.mkdir();
}
//创建文件
File file = new File(saveDir+File.separator+fileName);
//使用内存输出流的方式
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//将输入流写入到内存输出流中
byte[] buff = new byte[4096];
int len = -1;
while ((len = inputStream.read(buff)) != -1) {
baos.write(buff,0,len);
}
byte[] getData = baos.toByteArray();
//文件输出流
FileOutputStream fout = new FileOutputStream(file);
//将内存输出流写入磁盘
fout.write(getData);
//关闭输出输入流
fout.close();
//这里可以关闭,也可以不关闭,因为ByteArrayOutputStream的close方法是一个空实现,所以关闭也没有意义。
baos.close();
inputStream.close();
System.out.println("info:"+url+" download success");
}
两种方式最本质的却别在于那里呢???
在于第二种是先将输入流写入到了内存,在整个文件都写好后,在一次性的写入到磁盘中。
但是这样的方法是有缺陷的???
缺陷在于我们服务器的内存是有限的,当你往内存中写入的文件过于大的时候很容造成内存的溢出。
所以个人推荐使用第二种方式。