问题
I create ByteArrayOutputStream barr = new ByteArrayOutputStream(1);
, i.e. with capacity 1 bytes and write to it more than 1 byte barr.write("123456789000000".getBytes());
. No error occurs, I check the length of barr
it is 15. Why my writing was not blocked or wrapped? Is there a way to prevent of writing more than capacity and which outputstream
could be used for that?
I am very limited in available memory and don`t want to write there more than my limitations define
P.S. Thanks a lot for the answers! I had a following up question It could be great if you could look
回答1:
That is because the capacity that you specify to the constructor is the initial size of the buffer. If you write more data, the buffer will be automatically re-allocated with a larger size, to fit more data.
As far as I know, there is no way with ByteArrayOutputStream
to limit the growth of the buffer. You could use something else instead, for example a java.nio.ByteBuffer
, which has a fixed size.
回答2:
ByteArrayOutputStream
will grow the backing array if you try to write more bytes. This is usually thought of as a good thing.
If you want different behavior, you can always write your own OutputStream
implementation that throws an IOException if the number of bytes to write goes beyond the capacity.
ByteArrayOutputStream
is not final, so you can extend it. I think all you would have to do is override write(int)
and write(byte[], int, int)
to throw Exception if the number of bytes to write is more than the amount remaining. The fields buf
and count
are protected so your subclass should be able to see how much of the backing array is written to and the length of the array
回答3:
I had the same problem, and eventually turned up an existing implementation of the same thing within Hadoop - BoundedByteArrayOutputStream.java
来源:https://stackoverflow.com/questions/33018341/bytearrayoutputstream-capacity-restriction