この資料では、次の方法を使用してURLからファイルをダウンロードする方法を説明します。

  1. Apache Commons IO

  2. Java NIO

1. Apache Commons IO

1.1これは、インターネットからファイルをダウンロードするのが私の好みの方法です。シンプルでクリーンです。署名を読む:

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完全な例。

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 Java 7 NIOの例を試してください。

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完全な例。

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();
}

    }
}

=== 参考文献

.  https://commons.apache.org/proper/commons-io/[Commons IO]

.  https://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html[FileChannel

JavaDoc]。 https://docs.oracle.com/javase/7/docs/api/java/nio/channels/ReadableByteChannel.html[ReadableByteChannel

JavaDoc]

link://tag/common-io/[common io]link://タグ/ダウンロード/[ダウンロード]リンク://タグ/java/[java]リンク://タグ/java-io/[java.io]リンク://タグ/nio/[nio]link://tag/url/[url]