MrSnrub
MrSnrub

Reputation: 1183

Java: Keep binary file blob in memory for multiple uses (byte[]? ByteBuffer? ...?)

I read binary files from an InputStream and have to keep them in memory for further processing. The most obvious approach is to keep the read data of each file in a byte[] array. But I guess there are more elegant ways that provide some OO API around "file blobs" in memory. What would you recommend?

Upvotes: 1

Views: 1147

Answers (1)

Florian Weimer
Florian Weimer

Reputation: 33704

If everything fits into memory and the data is discarded quickly, use a byte[]s or non-direct (!) java.nio.ByteBuffers (which are just wrappers around byte arrays anyway). Byte buffers have the advantage that you can provide a reference to the same blob through which no changes to the blob can be made, using the asReadOnlyBuffer() method. With byte[], this requires a defensive copy. Regarding the additional overhead from ByteBuffer: The Hotspot compilers are pretty good at eliminating that, and your blobs seem to be fairly large, so the additional allocation should not matter.

Upvotes: 2

Related Questions