Java下载文件方法汇总

1,672 阅读2分钟

1 使用 JAVA IO

try (BufferedInputStream in = new BufferedInputStream(new URL(LARGE_FILE_URL).openStream());
  FileOutputStream fileOutputStream = new FileOutputStream(DOWNLOAD_LOCAL_FILENAME)) {

  byte dataBuffer[] = new byte[1024];
  int bytesRead;
  while ((bytesRead = in.read(dataBuffer, 01024)) != -1) {
    fileOutputStream.write(dataBuffer, 0, bytesRead);
  }
catch (IOException e) {
  e.printStackTrace();
}

2 使用 JAVA7 IO

try (InputStream in = new URL(LARGE_FILE_URL).openStream()) {
  Files.copy(in, Paths.get(DOWNLOAD_LOCAL_FILENAME), StandardCopyOption.REPLACE_EXISTING);
catch (IOException e) {
  e.printStackTrace();
}

3 使用 JAVA NIO

URL url = new URL(LARGE_FILE_URL);
try (ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
    FileOutputStream fileOutputStream = new FileOutputStream(DOWNLOAD_LOCAL_FILENAME);
    FileChannel fileChannel = fileOutputStream.getChannel()) {
  fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
}

4 使用 ApacheCommons

4.1 依赖

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

4.2 示例代码

int CONNECT_TIMEOUT = 10000;
int READ_TIMEOUT = 10000;
try {
  FileUtils.copyURLToFile(
      new URL(LARGE_FILE_URL),
      new File(DOWNLOAD_LOCAL_FILENAME),
      CONNECT_TIMEOUT,
      READ_TIMEOUT);
catch (IOException e) {
  e.printStackTrace();
}

5 使用 Jodd-http

5.1 依赖

<dependency>
  <groupId>org.jodd</groupId>
  <artifactId>jodd-http</artifactId>
  <version>5.1.4</version>
</dependency>

5.2 示例代码

jodd.http.HttpResponse response = HttpRequest.get(LARGE_FILE_URL).send();
byte[] bytes = response.bodyBytes();
FileUtils.writeByteArrayToFile(new File(DOWNLOAD_LOCAL_FILENAME), bytes);

6 使用 httpclient4

6.1 依赖

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.12</version>
</dependency>

6.2 示例代码

CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(LARGE_FILE_URL);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
try (InputStream is = entity.getContent()) {
  FileUtils.copyInputStreamToFile(is, new File(DOWNLOAD_LOCAL_FILENAME));
}
client.close();

7 使用 async-http-client

7.1 依赖

<dependency>
  <groupId>org.asynchttpclient</groupId>
  <artifactId>async-http-client</artifactId>
  <version>2.12.1</version>
</dependency>

7.2 示例代码

FileOutputStream stream = new FileOutputStream(DOWNLOAD_LOCAL_FILENAME);
AsyncHttpClient client = Dsl.asyncHttpClient();
client
    .prepareGet(LARGE_FILE_URL)
    .execute(
        new AsyncCompletionHandler<FileOutputStream>() {

          @Override
          public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
            stream.getChannel().write(bodyPart.getBodyByteBuffer());
            return State.CONTINUE;
          }

          @Override
          public FileOutputStream onCompleted(Response response) throws Exception {
            return stream;
          }
        })
    .get();

stream.getChannel().close();
client.close();

本文使用 mdnice 排版