Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to clear ByteArrayOutputStream

Tags:

java

Let's assume I have the following:

final ByteArrayOutputStream boas = new ByteArrayOutputStream();
final byte[] sample = {1,2,3,4,5,6,7,8,9,10};
boas.write(sample);

At this point the backing array byte buf[] within boas contains the 10 bytes above (and 22 padding bytes).

If I call reset on boas the count and size and all other factors indicate it's empty but internally byte buf[] remains unchanged and populated.

Is there anyway to truly clear this down without creating an entirely new ByteArrayOutputStream?

More generally, is there a reason why ByteArrayOutputStream behaves like this rather than emptying the byte[]?

like image 804
imrichardcole Avatar asked Feb 17 '16 07:02

imrichardcole


1 Answers

The Javadoc of ByteArrayOutputStream.reset() states

Resets the count field of this byte array output stream to zero, so that all currently accumulated output in the output stream is discarded. The output stream can be used again, reusing the already allocated buffer space.

Performance wise it makes sense to reuse an already allocated buffer.

If you want a different behaviour you can derive a class from ByteArrayOutputStream and override reset(). Both buf[] and count are protected members, so for instance you could clear buf if you want.

like image 51
wero Avatar answered Oct 01 '22 19:10

wero