java 38 lines · 6 steps

Streaming a file download with Java's HttpClient

A small class fetches a URL and streams the response body straight to disk without buffering it all in memory.

Explained by highlit
1import java.io.IOException;
2import java.io.InputStream;
3import java.net.URI;
4import java.net.http.HttpClient;
5import java.net.http.HttpRequest;
6import java.net.http.HttpResponse;
7import java.nio.file.Files;
8import java.nio.file.Path;
9import java.nio.file.StandardCopyOption;
10 
11public class RemoteFileDownloader {
12 
13 private final HttpClient httpClient;
14 
15 public RemoteFileDownloader(HttpClient httpClient) {
16 this.httpClient = httpClient;
17 }
18 
19 public long download(URI source, Path destination) throws IOException, InterruptedException {
20 HttpRequest request = HttpRequest.newBuilder(source)
21 .header("Accept", "application/octet-stream")
22 .GET()
23 .build();
24 
25 HttpResponse<InputStream> response =
26 httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());
27 
28 if (response.statusCode() != 200) {
29 throw new IOException("Unexpected status " + response.statusCode() + " for " + source);
30 }
31 
32 Files.createDirectories(destination.getParent());
33 
34 try (InputStream body = response.body()) {
35 return Files.copy(body, destination, StandardCopyOption.REPLACE_EXISTING);
36 }
37 }
38}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Streaming the response body to disk keeps memory use flat regardless of file size.
  2. 2Injecting the HttpClient makes the downloader configurable and testable rather than hardcoding transport details.
  3. 3A try-with-resources block guarantees the network stream closes even when the copy fails.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Streaming a file download with Java's HttpClient — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code