Java: Memory efficient ByteArrayOutputStream

前端 未结 9 555
一个人的身影
一个人的身影 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条回答
  •  野性不改
    2021-02-04 06:33

    MappedByteBuffer might be what you're looking for.

    I'm surprised it takes so much RAM to read a file in memory, though. Have you constructed the ByteArrayOutputStream with an appropriate capacity? If you haven't, the stream could allocate a new byte array when it's near the end of the 40 MB, meaning that you would, for example, have a full buffer of 39MB, and a new buffer of twice the size. Whereas if the stream has the appropriate capacity, there won't be any reallocation (faster), and no wasted memory.

提交回复
热议问题