简体   繁体   English

Java-NIO:将FileChannel.read()与offset-address / NullPointer一起使用

[英]Java-NIO: Use FileChannel.read() with offset-address / NullPointer

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? 有谁知道如何使用java-NIO的FileChannel.read(ByteBuffer[],int,int) -方法来仅读取文件的特定部分?

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

Throws a NullPointer while trying to execute the read()-method. 尝试执行read()方法时抛出NullPointer。 The buffer should be big enough, offsetAddress is 0, endAddress 255, the filesize is far beyond that. 缓冲区应该足够大,offsetAddress为0,endAddress为255,文件大小远不止于此。

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);
...

You are passing an empty array to the method, so reading throws an NPE because there is no buffer to read to. 您正在将一个空数组传递给该方法,因此读取将引发NPE,因为没有缓冲区可读取。

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, eg to read the header and the body from a file to different buffers: 但是似乎您做错了,应该使用FileChannel.read(ByteBuffer [],int,int)方法执行“分散读取”,其中将来自文件通道的数据顺序读取到一系列缓冲区中,例如从文件读取标头和正文到不同的缓冲区:

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. 将使用第一个headerLength字节填充标头,并使用随后的bodyLength字节填充body。

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: 如果您只是想将文件中的字节读入缓冲区(这似乎是OP想要的),则应使用FileChannel.read(ByteBuffer,long)方法,该方法将读取与字节数一样多的字节。给定的缓冲区:

ByteBuffer bb = ByteBuffer.allocate( bytesToRead );
FileChannel ch = FileChannel.open( somePath );
ch.read( bb, dataOffset );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM