Java: Memory efficient ByteArrayOutputStream

前端 未结 9 580
一个人的身影
一个人的身影 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:25

    ByteArrayOutputStream should be okay so long as you specify an appropriate size in the constructor. It will still create a copy when you call toByteArray, but that's only temporary. Do you really mind the memory briefly going up a lot?

    Alternatively, if you already know the size to start with you can just create a byte array and repeatedly read from a FileInputStream into that buffer until you've got all the data.

提交回复
热议问题