package com.github.pandafang.tool;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption; import org.apache.commons.io.FileUtils; /**
* 文件工具类
* @author panda fang
* @date 2017-08-26
* @version 1.0
*/
public class FileTool { /**
* 使用传统io stream 下载文件
* @param url
* @param saveDir
* @param fileName
*/
public static void download(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();
}
} } } /**
* 利用 commonio 库下载文件,依赖Apache Common IO ,官网 https://commons.apache.org/proper/commons-io/
* @param url
* @param saveDir
* @param fileName
*/
public static void downloadByApacheCommonIO(String url, String saveDir, String fileName) {
try {
FileUtils.copyURLToFile(new URL(url), new File(saveDir, fileName));
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 使用NIO下载文件, 需要 jdk 1.4+
* @param url
* @param saveDir
* @param fileName
*/
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();
}
}
} } /**
* 使用NIO下载文件, 需要 jdk 1.7+
* @param url
* @param saveDir
* @param fileName
*/
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();
} }
}

下载一个百度logo 测试一下

    public static void main(String[] args) {

        FileTool.downloadByNIO2("http://www.baidu.com/img/bd_logo1.png", "/home/panda/picture", "baidu_logo.png");
System.out.println("done..."); }

java 从网上下载文件的几种方式的更多相关文章

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

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

  2. 从后端接口下载文件的2种方式:get方式、post方式

    从后端接口下载文件的2种方式 一.get方式 直接使用: location.href='http://www.xxx.com/getFile?params1=xxx&params2=xxxx' ...

  3. Java下载文件的几种方式

    转发自博客园Sunny的文章 1.以流的方式下载 public HttpServletResponse download(String path, HttpServletResponse respon ...

  4. java 下载文件的两种方式和java文件的上传

    一:以网络的方式下载文件 try { // path是指欲下载的文件的路径. File file = new File(path); // 以流的形式下载文件. InputStream fis = n ...

  5. Asp.Net 下载文件的几种方式

    asp.net下载文件几种方式 protected void Button1_Click(object sender, EventArgs e) { /* 微软为Response对象提供了一个新的方法 ...

  6. php下载文件的一种方式

    <?php ob_start(); // $file_name="cookie.jpg"; $file_name="abc.jpg"; //用以解决中文不 ...

  7. asp.net 浏览器下载文件的四种方式

    // 方法一:TransmitFile实现下载 protected void Button1_Click(object sender, EventArgs e) { Response.ContentT ...

  8. C#从服务器下载文件的四种方式

    //方法一:TransmitFile实现下载 string fileName = "ss.docx"; //客户端预设的文件名,导出时可修改  string filePath = ...

  9. Java IO读写大文件的几种方式及测试

    读取文件大小:1.45G 第一种,OldIO: public static void oldIOReadFile() throws IOException{ BufferedReader br = n ...

随机推荐

  1. eAccelerator 配置参数详解

    eAccelerator配置参数如下: [eaccelerator]extension=eaccelerator.soeaccelerator.shm_size="64"eacce ...

  2. 获取浏览器用户代理(user-agent)

    获取浏览器用户代理(user-agent) 用户代理(user-agent)是浏览器客户端与服务器交互时的重要信息之一,用于帮助网站识别请求用户的浏览器类别,以便于网站发送相应的网页数据. 用户代理数 ...

  3. 3.nginx日志

    1. 自定义日志格式为json log_format json '{"@timestamp":"$time_iso8601",' '"@version ...

  4. 基于spring和mybatis的简单项目流程

    Mybatis整合Spring配置 第一部分:配置Spring框架 配置SpringMVC的步骤 配置流程图 SpringMVC配置 导入包(基本包5个,1日志依赖包,2webmvc支持包) 构建一个 ...

  5. Flyway数据库版本控制

    前言:最近工作上遇到个问题,项目开发过程中,开发代码可以通过svn来版本控制,但数据库又该如何来管理呢?多个人接触数据库,当对表.字段或数据修改后,又怎么来同步呢?经过苦寻,发现了个叫flyway的开 ...

  6. Boost application performance using asynchronous I/O-ref

    http://www.ibm.com/developerworks/linux/library/l-async/?S_TACT=105AGX52&S_CMP=cn-a-l Introducti ...

  7. no jpeg in java.library.path;java.lang.NoClassDefFoundError: Could not initialize class sun.awt.image.codec.JPEGImageEncoderImpl

    no jpeg in java.library.path;java.lang.NoClassDefFoundError: Could not initialize class sun.awt.imag ...

  8. Golang教程:包

    什么是包?为什么使用包? 到目前为止我们见到的 Go 程序都只有一个文件,文件中包含了一个main函数和几个其他函数.在实际中这种将所有代码都放在一个文件里的组织方式是不可行的.这样的组织方式使得代码 ...

  9. python 包管理工具Pipenv

    Kenneth Reitz的最新工具Pipenv可以用于简化Python项目中依赖项的管理. 它汇集了Pip,Pipfile和Virtualenv的功能,是一个强大的命令行工具. 入门 首先使用pip ...

  10. SP16580 QTREE7 - Query on a tree VII

    Description 一棵树,每个点初始有个点权和颜色(0/1) 0 u :询问所有u,v 路径上的最大点权,要满足u,v 路径上所有点的颜色都相同 1 u :反转u 的颜色 2 u w :把u 的 ...