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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Streaming the response body to disk keeps memory use flat regardless of file size.
- 2Injecting the HttpClient makes the downloader configurable and testable rather than hardcoding transport details.
- 3A try-with-resources block guarantees the network stream closes even when the copy fails.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
java
public record FixedWidthField(String name, int start, int end) { public String extract(String line) { int from = Math.min(start, line.length());
Parsing fixed-width text in Java
records
parsing
streams
Intermediate
7 steps
java
@RestController @RequestMapping("/api/quotes") public class QuoteStreamController {
Streaming market quotes with Spring WebFlux
reactive-streams
backpressure
server-sent-events
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/streaming-a-file-download-with-java-s-httpclient-explained-java-e53f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.