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

1

13

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);
Terza answered 21/12, 2011 at 23:15 Comment(2)
Rather than saving the data to a file and then reading the file and transferring the bytes, just cut out the middle man - send the bytes to the client without saving them to a file first.Stagg
Thanks Deco. I think my question wasn't well asked. Your comment is exactly what I wanted to do but I didn't know how to do it.Terza
F
15

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.

Foushee answered 21/12, 2011 at 23:21 Comment(1)
Specifying an encoding, of course... text.getBytes("UTF-8"), for example.Carbrey

© 2022 - 2024 — McMap. All rights reserved.