Java: Memory efficient ByteArrayOutputStream

前端 未结 9 557
一个人的身影
一个人的身影 2021-02-04 06:15

I\'ve got a 40MB file in the disk and I need to \"map\" it into memory using a byte array.

At first, I thought writing the file to a ByteArrayOutputStream would be the b

9条回答
  •  -上瘾入骨i
    2021-02-04 06:27

    For an explanation of the buffer growth behavior of ByteArrayOutputStream, please read this answer.

    In answer to your question, it is safe to extend ByteArrayOutputStream. In your situation, it is probably better to override the write methods such that the maximum additional allocation is limited, say, to 16MB. You should not override the toByteArray to expose the protected buf[] member. This is because a stream is not a buffer; A stream is a buffer that has a position pointer and boundary protection. So, it is dangerous to access and potentially manipulate the buffer from outside the class.

提交回复
热议问题