Say I want to read 1,100 bytes from a file using Java's ByteBuffer and FileChannel:
ByteBuffer buffer1 = ByteBuffer.allocate(1_100);
int bytesRead = fileChannel.read(buffer1)
The number of bytes to read is implicitly specified in the allocated size of the buffer. Fewer bytes could be read, but it is the byte buffer itself that indicates the number of bytes to read from the file.
Now, you want to read 1,200 bytes from the same file channel:
ByteBuffer buffer2 = ByteBuffer.allocate(1_200);
bytesRead = fileChannel.read(buffer2)
We can't reuse buffer1 and are forced to allocate a new buffer, buffer2.
What I'd like to see Java offer is a method of the form:
int read(ByteBuffer buffer, int offset, int length);
If I know the maximum number of bytes I will ever read I can allocate a single buffer just once and reuse it.
My application is a data processing system and need to read a specified number of bytes thousands of times a second in basically a while loop but find myself forced to allocate and clear buffers repeatedly.
Does anyone know of a way of reusing the same buffer? Or of a third-party library that I could use?
I'm aware of the slice() method, but from the JavaDoc, this creates a new buffer and so nothing gained.
You can make a ByteBuffer appear to be smaller by changing its limit:
ByteBuffer buffer = ByteBuffer.allocate(1_200);
buffer.limit(1_100);
int bytesRead = fileChannel.read(buffer);
// ...
buffer.clear();
// These two lines are the same as calling clear().
// buffer.limit(buffer.capacity());
// buffer.rewind();
bytesRead = fileChannel.read(buffer);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With