Java How to download a file from the Internet

摘要: This article shows you how to download a file from an URL by using the following methods :

This article shows you how to download a file from an URL by using the following methods :

  1. Apache Commons IO
  2. Java NIO

1. Apache Commons IO

1.1 This is still my prefer way to download a file from the Internet, simple and clean. Read the signature :

org.apache.commons.io.FileUtils
//int = number of milliseconds
public static void copyURLToFile(URL source, File destination,
            int connectionTimeout, int readTimeout) throws IOException

1.2 Full example.

HttpUtils.java
package com.mkyong;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class HttpUtils {
    public static void main(String[] args) {
        String fromFile = "ftp://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest";
        String toFile = "F:\\arin.txt";
        try {
            //connectionTimeout, readTimeout = 10 seconds
            FileUtils.copyURLToFile(new URL(fromFile), new File(toFile), 10000, 10000);
        } catch (IOException e) {
            e.printStackTrace();

1.3 Maven

pom.xml
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

1.4 Gradle

build.gradle
dependencies {
    compile 'commons-io:commons-io:2.5'

2. Java NIO

2.1 Try Java 7 NIO example.

	URL website = new URL(fromFile);
	ReadableByteChannel rbc = Channels.newChannel(website.openStream());
	FileOutputStream fos = new FileOutputStream(toFile);
	fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
	fos.close();
	rbc.close();

2.2 Full example.

HttpUtils.java
package com.mkyong;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class HttpUtils {
    public static void main(String[] args) {
        String fromFile = "ftp://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest";
        String toFile = "F:\\arin.txt";
        try {
            URL website = new URL(fromFile);
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            FileOutputStream fos = new FileOutputStream(toFile);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
            rbc.close();
        } catch (IOException e) {
            e.printStackTrace();

References

  1. Commons IO
  2. FileChannel JavaDoc
  3. ReadableByteChannel JavaDoc

上一篇: Java 8 Tutorials
下一篇: java.lang.NoClassDefFoundError: com/fasterxml/jackson/annotation/JsonMerge
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号