Java servlet and IO: Create a file without saving to disk and sending it to the user

LatinCanuck picture LatinCanuck · Dec 22, 2011 · Viewed 22.8k times · Source

I`m hoping can help me out with a file creation/response question. I know how to create and save a file. I know how to send that file back to the user via a ServletOutputStream.

But what I need is to create a file, without saving it on the disk, and then send that file via the ServletOutputStream.

The code above explains the parts that I have. Any help appreciated. Thanks in Advance.

// This Creates a file
//
String   text = "These days run away like horses over the hill";
File     file = new File("MyFile.txt");
Writer writer = new BufferedWriter(new FileWriter(file));
writer.write(text);
writer.close();

// Missing link goes here
//

// This sends file to browser
//
InputStream inputStream = null;
inputStream = new FileInputStream("C:\\MyFile.txt");

byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();

int bytesRead;
while (  (bytesRead = inputStream.read(buffer)) != -1)
   baos.write(buffer, 0, bytesRead);

response.setContentType("text/html");
response.addHeader("Content-Disposition", "attachment; filename=Invoice.txt");

byte[] outBuf = baos.toByteArray();
stream = response.getOutputStream();
stream.write(outBuf);

Answer

Stephen Rudolph picture Stephen Rudolph · Dec 22, 2011

You don't need to save off a file, just use a ByteArray stream, try something like this:

inputStream = new ByteArrayInputStream(text.getBytes());

Or, even simpler, just do:

stream.write(text.getBytes());

As cHao suggests, use text.getBytes("UTF-8") or something similar to specify a charset other than the system default. The list of available charsets is available in the API docs for Charset.