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

26,072

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.

Share:
26,072
LatinCanuck
Author by

LatinCanuck

Updated on July 09, 2022

Comments

  • LatinCanuck
    LatinCanuck almost 2 years

    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);
    
  • cHao
    cHao over 12 years
    Specifying an encoding, of course... text.getBytes("UTF-8"), for example.