0

Does anyone know how to use the FileChannel.read(ByteBuffer[],int,int)-method of java-NIO to read just a certain part of a file?

ByteBuffer[] bb = new ByteBuffer[(int) fChannel.size()];
fChannel.read(bb, offsetAddress, endAddress);

Throws a NullPointer while trying to execute the read()-method. The buffer should be big enough, offsetAddress is 0, endAddress 255, the filesize is far beyond that.

Franz Kafka
  • 10,623
  • 20
  • 93
  • 149
chollinger
  • 1,097
  • 5
  • 20
  • 34
  • So you are creating a ByteBuffer per every byte of your file? What is the point of that? What is the size of your file? – Edwin Dalorzo May 09 '12 at 10:29

2 Answers2

0

You are creating an array but you are not putting anything inside of it.

Perhaps something like:

ByteBuffer[] bb = new ByteBuffer[(int) fChannel.size()];
bb[0] = ByteBuffer.allowcate(1024);
bb[1] = ByteBuffer.allowcate(1024);
...
Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
  • yeah, sure, forgot to post that. filling the array with some hard-coded bb's also gives me a nullpointer. so how many byte-buffers need to be allocated to the array? i simply don't get the way it works and therefore dunno how to _properly_ use it. – chollinger May 09 '12 at 10:13
  • 1
    @user1004816 So why use it at all? Why not just use write(ByteBuffer) and keep your life simple? If you don't *have* multiple ByteBuffers to write, creating them just to satisfy an API that you otherwise don't need is pointless. – user207421 May 09 '12 at 23:24
0

You are passing an empty array to the method, so reading throws an NPE because there is no buffer to read to.

But it seems you are doing it wrong, the FileChannel.read(ByteBuffer[],int,int) method is supposed to perform a "scattering read", in which data from the file channel is read sequentially to a series of buffers, e.g. to read the header and the body from a file to different buffers:

ByteBuffer header = ByteBuffer.allocate( headerLength );
ButeBuffer body = ByteBuffer.allocate( bodyLength );
FileChannel ch = FileChannel.open( somePath );
ch.read( new ByteBuffer[]{ header, body }, dataOffset, headerLength + bodyLength );

Will populate header with the first headerLength bytes, and body with the following bodyLength bytes.

If you just want to read bytes from a file into a buffer (which seems to be what what OP wanted), you should use the FileChannel.read(ByteBuffer,long) method, which will read as many bytes as there are remaining bytes in the given buffer:

ByteBuffer bb = ByteBuffer.allocate( bytesToRead );
FileChannel ch = FileChannel.open( somePath );
ch.read( bb, dataOffset );
jtatria
  • 527
  • 3
  • 12