Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedOutputStream vs ByteArrayOutputStream

Tags:

Is there any advantage in wrapping a BufferedOutputStream around a ByteArrayOutputStream instead of just using the ByteArrrayOutputStream by itself?

like image 797
Hank Avatar asked Jul 25 '11 20:07

Hank


People also ask

What is the difference between ByteArrayOutputStream and FileOutputStream?

The ByteArrayOutputStream is more memory hogging since it stores the entire content in Java's memory (in flavor of a byte[] ). The FileOutputStream writes to disk directly and is hence less memory hogging.

What is a ByteArrayOutputStream?

Java ByteArrayOutputStream class is used to write common data into multiple files. In this stream, the data is written into a byte array which can be written to multiple streams later. The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.

What is the use of Bufferedoutputstream?

Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.

Do we need to close ByteArrayOutputStream?

In summary: It does no harm to flush() or close() a bare ByteArrayOutputStream . It is just unnecessary.


2 Answers

Generally BufferedOutputStream wrapper is mostly used to avoid frequent disk or network writes. It can be much more expensive to separately write a lot of small pieces than make several rather large operations. The ByteArrayOutputStream operates in memory, so I think the wrapping is pointless.

If you want to know the exact answer, try to create a simple performance-measuring application.

like image 103
Binus Avatar answered Nov 25 '22 10:11

Binus


Absolutely none. Though BufferedWriter and BufferedReader do offer extra functionality were you to be operating on strings.

like image 21
Dunes Avatar answered Nov 25 '22 11:11

Dunes