Java File Stream to Frontend: Complete Guide

In Java, you can use Servlet to send a file stream back to the front-end. Here is a simple example code:

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filePath = "/path/to/your/file.txt";
        File file = new File(filePath);
        
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        
        FileInputStream fileInputStream = new FileInputStream(file);
        OutputStream outputStream = response.getOutputStream();
        
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        
        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        
        fileInputStream.close();
        outputStream.close();
    }
}

In the code above, we start by specifying the file path to download, then set the appropriate Content-Type and Content-Disposition headers, write the file stream to the response output stream, and finally close the input and output streams. When the browser requests the /download path, a download file dialog will pop up, allowing users to choose to save the file or open it directly.

bannerAds