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.
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
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?