0

I am working on spring boot application which needs to send the workbook created by apache poi workbook document to the client via REST API, although I am able to send it, I wanted to know the efficient way to send the file over the wire.

  1. I wrote the file on disk and sent the file to the client and API is done, but now I have to have additional code to remove such stale files so I decided to go with 2nd approach

  2. Write file in ByteArrayOutputStream and then pass the byte Array to create spring resource and it will send the file without writing it to disk and the problem is solved.

but then I found many links that discuss efficiency and memory issues of ByteArrayOutputStream like this one -->. stack overflow

As one of the answers explains BufferedReader is more efficient than ByteArrayOutputStream for writing files efficiently, so I came up with the below code.

    ByteArrayOutputStream byteOut= new ByteArrayOutputStream();
    BufferedOutputStream bufOut = new BufferedOutputStream(bos);
    String content = "lets imagin huge amount of data"; 
    bufOut.write(content.getBytes());
    bufOut.flush();
    bufOut.close();
    bos.close();
    System.out.println(new String(byteOut.toByteArray()));

I am able to write on ByteArrayOutputStream directly without BufferedOutputStream but I am thinking about the efficiency of writing buffered data instead of byte by byte.

Is the above code correct to be used in given situation?

Akshay Naik
  • 669
  • 1
  • 6
  • 22
  • 2
    Why don't you just write directly to the client, without any files or `ByteArrayOutputStreams`? That would use the least amount of memory. Wrapping a `BufferedStream` over a `BAOS` is useless, as you're writing to memory anyway. – Kayaman Nov 02 '19 at 18:04
  • Approach 1 is better because you consume less memory. While writing, you can use SXSSF and most calls are the same, except that only a certain number of rows are in memory. You don't have to keep the whole file in memory, in this case if "content" is large enough your application will run out of memory. – user12047085 Nov 02 '19 at 18:09
  • 1
    The question you link discusses something entirely different than efficiency and memory issues. When you wrap a `BufferedOutputStream` around a `ByteArrayOutputStream`, you're still using a `ByteArrayOutputStream`. It is unlikely that you will gain any efficiency this way, but you will be consuming more memory than just using the `ByteArrayOutputStream` directly. – Mark Rotteveel Nov 02 '19 at 18:13
  • So I will avoid using BufferedOutputStream, the reason behind using ByteArrayOutputStream was to avoid writing the files on disk before sending it. I also liked the idea given by @Kayaman of writing the file directly to the client . – Akshay Naik Nov 03 '19 at 07:07

0 Answers0