Download File From: Byte Array Java Best
: Setting this to attachment with a filename tells the browser to open a "Save As" dialog.
If you are working with legacy Java EE or standard Jakarta Servlets, you manually write to the HttpServletResponse output stream.
In a modern web application, you typically want to return a ResponseEntity or ResponseEntity . The browser needs specific HTTP headers to recognize the response as a file download rather than plain text. download file from byte array java
try (FileOutputStream fos = new FileOutputStream("output.txt")) { fos.write(data); } Use code with caution. Best Practices & Performance
In Java, downloading a file from a byte array typically involves one of two scenarios: sending the bytes from a server to a user's browser via a web framework like or Servlets , or saving those bytes directly to a local disk using Standard I/O . 1. Downloading via Spring Boot (REST API) : Setting this to attachment with a filename
If your goal is to "download" a byte array from your application memory to a local folder on the server or a desktop, use for the cleanest implementation. Java NIO (Recommended):
@GetMapping("/download") public ResponseEntity downloadFile() { // 1. Your source byte array (e.g., from a DB or generated PDF) byte[] data = "Hello, this is a downloadable file!".getBytes(); // 2. Set headers to trigger a download prompt HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // Generic binary headers.setContentDisposition(ContentDisposition.attachment() .filename("my-file.txt") .build()); return ResponseEntity.ok() .headers(headers) .contentLength(data.length) .body(data); } Use code with caution. The browser needs specific HTTP headers to recognize
import java.nio.file.Files; import java.nio.file.Paths; byte[] data = ...; Files.write(Paths.get("C:/downloads/my-file.jpg"), data); Use code with caution.