One way to stream data to the client, is to use the PrintWriter, a library which allows you to directly manipulate the output stream which is sent to the client. One of the benefits of streaming the output to the client with PrintWriter, is the ability to send data as it is generated; instead of having to buffer all of the data on the server, then send the data to the client after the entire set is generated.
For convenience and especially for large files, it is important to modify the HTTP headers in HttpServletResponse, instructing the client’s browser to save the file to disk.
The following is a minimal example, which shows how to dump a dummy CSV text file as a downloadable file in a struts Action Servlet.
public class CsvDataDumpAction extends Action {
public ActionForward execute
(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
{
// declare the PrintWriter object for later instantiation
PrintWriter pw = null;
// modify the HTTP response header, so the file is downloaded as DataDump.txt
response.setHeader("Content-disposition", "attachment; filename=DataDump.txt");
response.setContentType("application/octet-stream");
// catch the IOException generated by the PrintWriter
try {
// Sample header with four fields
String header = "Field1,Field2,Field3,Field4";
pw.println(header);
// flush the buffer, sending the header line to the client
pw.flush();
// generate 1000 lines of dummy test data, with the field name, followed by the number of the row
for(int i = 0; i < 1000; i++) {
pw.println("Field1_"+i+",Field2_"+i+",Field3_"+i+",Field4_"+i);
// flush the buffer after each line is generated,
// sending the data to the client as it is generated
pw.flush();
}
// show stack traces for the PrintWriter in the logs
} catch (IOException e) { e.printStackTrace(); }
return null;
}
}