Search code examples
javaarraysappendoutputstreamhttp-status-code-504

Java, is there a way to append byte array using servlet outputstream instead of overwrite?


everyone. I am using apache poi to generate excel format file, I didn't store it on my disk, just byte array, then I use outputstream to write the byte array to client, so the client can download the excel file. Something like this:

OutputStream outputStream = response.getOutputStream();
byte[] fileData = generateDownloadFile(paramters);
outputStream.write(temp);
outputStream.flush();

However, I'm wondering if there exists a method that I can append the byte array to client instead of write it once, so I can generate some byta array then flush them, then generate some and flush them, and finally close connection. If using outputstream's write method doing this, the later overwrites the former.

Why I need this? I just want to send something back to client in a short duration, if I generate the whole excel file byte array, then flush it back, the connection may be already closed and cause a 504 error.

I haved tried:

  • append method in PrintWriter class. But it didn't work, since I need to send byte instead of character, I cannot open the file using MSExcel when through PrintWriter.
  • I also tried to use socket. But socket still need to use outputstream, like new Socket().getOutputStream();.

I'm an expert in Java, even not familiar. Can anyone help to figure out? Thanks.


Solution

  • Output has a write method to add bytes with an offset:

       outputstream.write(bytes, alreadySentSizeInBytes, 
                                              bytes.length);
    

    Please check if this works