4

I want to export Data from a Rich Faces Data Table I have created outputStream from the data in the Data Table. Now want to send this OutputStream to browser and let it save. How can I do this?

FileOutputStream stream = new FileOutputStream(new File(PATH));

OutputStream out = myMthodToCreateOutPutStream();

Now how to save this out to browser .

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
waseemwk
  • 1,499
  • 3
  • 15
  • 44

1 Answers1

12

It's not clear where you are reading your data from. You need to create an InputStream to read the data.

Then, you first need to set the response headers to

HttpServletResponse.setHeader("Content-Disposition", "attachment; filename=datafile.xls");

Use whatever filename you need.

Then set the mime-type:

response.setContentType("application/vnd.ms-excel");

Use the mime-type you need.

Then need to use the response object to get its outputstream -

OutputStream outStream = response.getOutputStream();

Now write to it:

byte[] buf = new byte[4096];
int len = -1;

//Write the file contents to the servlet response
//Using a buffer of 4kb (configurable). This can be
//optimized based on web server and app server
//properties
while ((len = inStream.read(buf)) != -1) {
    outStream.write(buf, 0, len);
}

outStream.flush();
outStream.close();
Rajesh J Advani
  • 5,585
  • 2
  • 23
  • 35