Search code examples
javaniobytebufferfilechannel

Reading certain number of bytes into ByteBuffer


I have a binary file of 10MB. I need to read it in chunks of different size (e.g 300, 273 bytes). For reading I use FileChannel and ByteBuffer. Right now for each iteration of reading I allocate new ByteBuffer of size, that I need to read.

Is there possible to allocate only once (lets say 200 KB) for ByteBuffer and read into it (300 , 273 bytes etc. )? I will not read more than 200KB at once. The entire file must be read.

UPD

public void readFile (FileChannel fc, int amountOfBytesToRead)
{
    ByteBuffer bb= ByteBuffer.allocate(amountOfBytesToRead);
    fc.read(bb);
    bb.flip();
    // do something with bytes
    bb = null;
}

I can not read whole file at once due to memory constraints. That's why I performing reading in chunks. Efficiency is also very important (that is why I don't want to use my current approach with multiple allocations). Thanks


Solution

  • Declare several ByteBuffers of the sizes you need and use scatter-read: read(ByteBuffer[] dsts, ...).

    Or forget about NIO and use DataInputStream,readFully(). If you put a BufferedInputStream underneath you won't suffer any performance loss: it may even be faster.