Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 556
LatinCanuck Avatar asked Dec 21 '11 23:12

LatinCanuck


People also ask

How to send file in Java via POST without saving it to disk?

Use a ByteArrayResource instead: String fileContent = generateFile(); ByteArrayResource bar = new ByteArrayResource(fileContent. getBytes()); This way you will not have to create any resource on disk but keep it in memory instead.

How do you create a file and write data in Java?

Example 1: Java Program to Create a File java is equivalent to // currentdirectory/JavaFile. java File file = new File("JavaFile. java"); We then use the createNewFile() method of the File class to create new file to the specified path.


1 Answers

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.

like image 180
Stephen Rudolph Avatar answered Oct 29 '22 06:10

Stephen Rudolph