Nov 10, 2018

Example: Download File From Web (JAVA)

If you download file from JSF, see here

response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; fileName=yourFileName");

ServletOutputStream out = response.getOutputStream();
StringBuilder writer = new StringBuilder();

//use csv as example, use .csv as extension in your file name. you can use "text/csv" as your content type for csv file, but octet-stream is more generic.
writer.append("firstname");
writer.append(',');
writer.append("lastname");
writer.append(',');
writer.append("email");
writer.append('\n');

//c is a variable
writer.append(c.getFirstname());
writer.append(',');
writer.append(c.getLastname());
writer.append(',');
writer.append(c.getEmail());
writer.append('\n');

byte[] bytes = writer.toString().getBytes();
out.write(bytes);
out.flush();
out.close();

For csv, you can use

response.setContentType("text/csv");

os = response.getOutputStream();

PrintStream ps = new PrintStream(os);
ps.print();
ps.print(',');
// ...
ps.println();
os.close();