java下载网络文件的N种方式
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种方式的更多相关文章
- java读取XML文件的四种方式
java读取XML文件的四种方式 Xml代码 <?xml version="1.0" encoding="GB2312"?> <RESULT& ...
- Java 读取 .properties 文件的几种方式
Java 读取 .properties 配置文件的几种方式 Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中.然而 XML 配置文件需要通过 ...
- 网络编程(一):用C#下载网络文件的2种方法
使用C#下载一个Internet上的文件主要是依靠HttpWebRequest/HttpWebResonse和WebClient.具体处理起来还有同步和异步两种方式,所以我们其实有四种组合. 1.使用 ...
- 前端调用后端接口下载excel文件的几种方式
今天有一个导出相应数据为excel表的需求.后端的接口返回一个数据流,一开始我用axios(ajax类库)调用接口,返回成功状态200,但是!但是浏览器没有自动下载excel表,当时觉得可能是ajax ...
- 【开发笔记】- Java读取properties文件的五种方式
原文地址:https://www.cnblogs.com/hafiz/p/5876243.html 一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供j ...
- java 下载网络文件
1.FileUtils.copyURLToFile实现: import java.io.File; import java.net.URL; import org.apache.commons.io. ...
- java上传文件常见几种方式
1.ServletFileUpload 表单提交中当提交数据类型是multipare/form-data类型的时候,如果我们用servlet去做处理的话,该http请求就会被servlet容器,包装成 ...
- java读取excel文件的两种方式
方式一: 借用 package com.ij34.util; /** * @author Admin * @date 创建时间:2017年8月29日 下午2:07:59 * @version 1.0 ...
- STM32下载Bin文件的几种方式
一.STM32 ST-LINK Utility 1.下载安装软件 官网下载地址:http://www.st.com/zh/development-tools/stsw-link004.html 百度网 ...
- 【文件下载】Java下载文件的几种方式
[文件下载]Java下载文件的几种方式 摘自:https://www.cnblogs.com/sunny3096/p/8204291.html 1.以流的方式下载. public HttpServl ...
随机推荐
- Stanford CoreNLP无法生成实例对象
在服务器上运行Stanford,今日无法启动"StanfordCoreNLP"了,就是运行下面代码一直在运行,不结束,不报错. from stanfordcorenlp impor ...
- OCI runtime exec failed: exec failed: unable to start container process: exec: "mongo": executable file not found in $PATH: unknown
前言: 今天按照以往在Docker安装MongoDB的方式安装,但是到最后使用mongo命令执行mongodb命令的时候一直执行不成功,最后还是按照官网的Issues解决了. 创建并运行一个Mongo ...
- Vscode设置标签页多行显示
1.设置标签页多行展示的方法 文件–>首选项–>设置 2.勾选多行显示按钮 3.显示效果
- MySQL 全局锁、表级锁、行级锁,你搞清楚了吗?
大家好,我是小林. 最近重新补充了<MySQL 有哪些锁>文章内容: 增加记录锁.间隙锁.net-key 锁 增加插入意向锁 增加自增锁为 innodb_autoinc_lock_mode ...
- SpringCloud微服务实战——搭建企业级开发框架(四十六):【移动开发】整合uni-app搭建移动端快速开发框架-环境搭建
近年来uni-app发展势头迅猛,只要会vue.js,就可以开发一套代码,发布移动应用到iOS.Android.Web(响应式).以及各种小程序(微信/支付宝/百度/头条/飞书/QQ/快手/钉钉/ ...
- C++智能指针的enable_shared_from_this和shared_from_this机制
前言 之前学习muduo网络库的时候,看到作者陈硕用到了enable_shared_from_this和shared_from_this,一直对此概念是一个模糊的认识,隐约记着这个机制是在计数器智能指 ...
- 第2-1-3章 docker-compose安装FastDFS,实现文件存储服务
目录 4 docker-compose安装FastDFS 4.1 docker-compose-fastdfs.yml 4.2 nginx.conf 4.3 storage.conf 4.4 测试 4 ...
- .NET7 gRPC JSON转码+OpenAPI
gRPC JSON转码 gRPC JSON 转码允许浏览器应用调用 gRPC 服务,就像它们是使用 JSON 的 RESTful API 一样. 浏览器应用不需要生成 gRPC 客户端或了解 gRPC ...
- Vue2 到 Vue3,重温这 5 个常用的 API
距离Vue3发布已经过去一年多时间了,从Vue2到Vue3是一个不小的升级,包括周边生态等.虽然目前大多数开发者们在使用的仍旧以Vue2为准,但Vue3显然是Vue开发者们未来必须面对的,而且前不久V ...
- 2022-11-06 Acwing每日一题
本系列所有题目均为Acwing课的内容,发表博客既是为了学习总结,加深自己的印象,同时也是为了以后回过头来看时,不会感叹虚度光阴罢了,因此如果出现错误,欢迎大家能够指出错误,我会认真改正的.同时也希望 ...