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)

java下载网络文件的N种方式的更多相关文章

  1. java读取XML文件的四种方式

    java读取XML文件的四种方式 Xml代码 <?xml version="1.0" encoding="GB2312"?> <RESULT& ...

  2. Java 读取 .properties 文件的几种方式

    Java 读取 .properties 配置文件的几种方式   Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中.然而 XML 配置文件需要通过 ...

  3. 网络编程(一):用C#下载网络文件的2种方法

    使用C#下载一个Internet上的文件主要是依靠HttpWebRequest/HttpWebResonse和WebClient.具体处理起来还有同步和异步两种方式,所以我们其实有四种组合. 1.使用 ...

  4. 前端调用后端接口下载excel文件的几种方式

    今天有一个导出相应数据为excel表的需求.后端的接口返回一个数据流,一开始我用axios(ajax类库)调用接口,返回成功状态200,但是!但是浏览器没有自动下载excel表,当时觉得可能是ajax ...

  5. 【开发笔记】- Java读取properties文件的五种方式

    原文地址:https://www.cnblogs.com/hafiz/p/5876243.html 一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供j ...

  6. java 下载网络文件

    1.FileUtils.copyURLToFile实现: import java.io.File; import java.net.URL; import org.apache.commons.io. ...

  7. java上传文件常见几种方式

    1.ServletFileUpload 表单提交中当提交数据类型是multipare/form-data类型的时候,如果我们用servlet去做处理的话,该http请求就会被servlet容器,包装成 ...

  8. java读取excel文件的两种方式

    方式一: 借用 package com.ij34.util; /** * @author Admin * @date 创建时间:2017年8月29日 下午2:07:59 * @version 1.0 ...

  9. STM32下载Bin文件的几种方式

    一.STM32 ST-LINK Utility 1.下载安装软件 官网下载地址:http://www.st.com/zh/development-tools/stsw-link004.html 百度网 ...

  10. 【文件下载】Java下载文件的几种方式

    [文件下载]Java下载文件的几种方式  摘自:https://www.cnblogs.com/sunny3096/p/8204291.html 1.以流的方式下载. public HttpServl ...

随机推荐

  1. Period of an Infinite Binary Expansion 题解

    Solution 简单写一下思考过程,比较水的数论题 第一个答案几乎已经是可以背下来的,在此不再赘述 考虑我们已经知道了\((p,q)\),其中\((p \perp q) \wedge (q \per ...

  2. JavaScript基本语法(函数与对象)

    3.函数 #①内置函数 内置函数:系统已经声明好了可以直接使用的函数. #[1]弹出警告框 alert("警告框内容");   #[2]弹出确认框 用户点击『确定』返回true,点 ...

  3. 后端框架学习-----mybatis(使用mybatis框架遇到的问题)

    1.配置文件没有注册(解决:在核心配置文件中注册mapper,注册有三种形式.资源路径用斜杆,包和类用点) <mappers> <!--每一个mapper.xml文件都需要在myba ...

  4. 在IDEA中使用Maven将SpringBoot项目打成jar包、同时运行打成的jar包(前后端项目分离)

    1.maven教程官网 https://m.runoob.com/maven/ 2.理解Maven的构建生命周期(clean.Package) 3.在项目中使用maven进行打包 4.运行打包好的ja ...

  5. 驱动开发:内核监视LoadImage映像回调

    在笔者上一篇文章<驱动开发:内核注册并监控对象回调>介绍了如何运用ObRegisterCallbacks注册进程与线程回调,并通过该回调实现了拦截指定进行运行的效果,本章LyShark将带 ...

  6. 9.为url添加可选的后缀

    为url添加可选的后缀 在drf的机制中,响应数据的格式不再与单一内容类型连接,可以同时享有json格式或html格式,我们可以为api路径添加格式后缀的支持,使用格式后缀给我们明确指定了给定格式的u ...

  7. linux清理内存缓存cache

    Linux服务器有自己先进的内存管理机制,有时候会发现我们系统的buff/cache内存占用会越来越高,操作系统也有卡顿的情况,遇到这种情况,不妨试试下面的方法. 1步骤一:我们先查看物理内存占用情况 ...

  8. 修改input标签里面的提示文字(placeholder)的样式

    使用 ::-webkit-input-placeholder 伪类 input::-webkit-input-placeholder{ // 修改字体大小 font-size:12px; // 修改文 ...

  9. 09 | 从容器到容器云:谈谈Kubernetes的本质

    你好,我是张磊.今天我和你分享的主题是:从容器到容器云,谈谈Kubernetes的本质. 在前面的四篇文章中,我以Docker项目为例,一步步剖析了Linux容器的具体实现方式.通过这些讲解你应该能够 ...

  10. TreeUtils工具类一行代码实现列表转树 实战Java8 三级菜单 三级分类 附视频

    一.序言 在日常一线开发过程中,总有列表转树的需求,几乎是项目的标配,比方说做多级菜单.多级目录.多级分类等,有没有一种通用且跨项目的解决方式呢?帮助广大技术朋友给业务瘦身,提高开发效率. 本文将基于 ...