java / intermediate
Snippet
Low-Memory Large File Streaming via StreamingResponseBody
Loading massive datasets into memory before sending causes OutOfMemoryError crashes. StreamingResponseBody allows Spring MVC to write data directly to the client HTTP OutputStream in chunks across an asynchronous worker thread, keeping heap utilization constant.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@RestController@RequestMapping("/export")public class DataExportController {private final LargeDatasetService datasetService;public DataExportController(LargeDatasetService datasetService) {this.datasetService = datasetService;}@GetMapping("/records")public ResponseEntity<StreamingResponseBody> streamExport() {StreamingResponseBody stream = outputStream -> {try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream))) {datasetService.streamRecords(record -> {writer.write(record.toCsvLine());writer.newLine();});writer.flush();}};return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=export.csv").contentType(MediaType.TEXT_PLAIN).body(stream);}}
spring
Breakdown
1
StreamingResponseBody stream = outputStream -> { ... };
Defines a functional callback that Spring executes asynchronously with direct access to the client output stream.
2
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)))
Wraps the raw binary stream with a buffered character writer for efficient text flushing.
3
datasetService.streamRecords(record -> { ... });
Consumes records line-by-line from the persistence layer without materializing the full collection in memory.
4
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=export.csv")
Instructs the receiving client browser to download the incoming byte stream as a CSV file.