java下载网络文件的N种方式

通过java api下载网络文件的方法有很多,主要方式有以下几种:

1、使用 common-io库下载文件,需要引入commons-io-2.6.jar

public static void downloadByCommonIO(String url, String saveDir, String fileName) {
try {
FileUtils.copyURLToFile(new URL(url), new File(saveDir, fileName));
} catch (IOException e) {
e.printStackTrace();
}
}

2、使用NIO下载文件,需要 jdk 1.4+

public static void downloadByNIO(String url, String saveDir, String fileName) {
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
FileChannel foutc = null;
try {
rbc = Channels.newChannel(new URL(url).openStream());
File file = new File(saveDir, fileName);
file.getParentFile().mkdirs();
fos = new FileOutputStream(file);
foutc = fos.getChannel();
foutc.transferFrom(rbc, 0, Long.MAX_VALUE);

} catch (IOException e) {
e.printStackTrace();
} finally {
if (rbc != null) {
try {
rbc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (foutc != null) {
try {
foutc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

3、使用NIO下载文件,需要 jdk 1.7+

public static void downloadByNIO2(String url, String saveDir, String fileName) {
try (InputStream ins = new URL(url).openStream()) {
Path target = Paths.get(saveDir, fileName);
Files.createDirectories(target.getParent());
Files.copy(ins, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}

4、使用传统io stream下载文件

public static void downloadByIO(String url, String saveDir, String fileName) {
BufferedOutputStream bos = null;
InputStream is = null;
try {
byte[] buff = new byte[8192];
is = new URL(url).openStream();
File file = new File(saveDir, fileName);
file.getParentFile().mkdirs();
bos = new BufferedOutputStream(new FileOutputStream(file));
int count = 0;
while ((count = is.read(buff)) != -1) {
bos.write(buff, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

5、使用Byte Array获得stream下载文件

public static void  downLoadFromUrl(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 input = conn.getInputStream();
// 获取自己数组
byte[] getData = readInputStream(input);

// 文件保存位置
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+File.separator+fileName);
FileOutputStream output = new FileOutputStream(file);
output.write(getData);
if(output!=null){
output.close();
}
if(input!=null){
input.close();
}
System.out.println("download success!!");
}

public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[10240];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}

转载自:java下载网络文件的N种方式 - Jaywen - 博客园 (cnblogs.com)

最新文章

  1. 判断一个对象是jQuery对象还是DOM对象
  2. JMeter学习(一)工具简单介绍
  3. cocos2d CCArray
  4. VM虚拟机无法拖拽、粘贴、复制
  5. AngularJS 学习笔记二
  6. HDU-4627 The Unsolvable Problem 简单数学
  7. tyvj1297 小气的小B
  8. php测试时不出现错误信息
  9. mark_May
  10. caioj 1236 最近公共祖先 树倍增算法模版 倍增
  11. The 3rd tip of DB QueryAnalyzer
  12. OAuth 2.0详解
  13. 1. nginx添加自定义http模块(简单)
  14. Linux查看和修改时间、日期
  15. NodeJs 使用 multer 实现文件上传
  16. C# WPF 文件复制,相对路径
  17. jqgrid 配置行号及行号的宽度
  18. 【算法复习】codevs1022 匈牙利算法
  19. 【运维技术】kafka三实例集群环境搭建及测试使用
  20. [置顶] Unity2d引入新功能SpriteAtlas,Sprite新的图集方式

热门文章

  1. 认识 Redis client-output-buffer-limit 参数与源码分析
  2. react 可视化编辑器1
  3. laravel config()获取null
  4. Asp.Net Core MVC传值 Asp.Net Core API 前台写法
  5. SpringBoot→Maven项目快速搭建
  6. Python基础之面向对象:3、继承与派生
  7. day11-Servlet01
  8. 二叉搜索树 - C++ 实现
  9. NC 使用Nginx实现https的反向代理
  10. Spark通过打jar包形式提交任务