我试图读取4个字节,它们代表一个int,位于二进制文件中字节位置64处。
这就是我尝试过的:
package testbinaryfile2;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class TestBinaryFile2 {
public static void main(String[] args) throws IOException {
FileChannel fc;
ByteBuffer indexField = ByteBuffer.allocate(4);
fc = (FileChannel.open(Paths.get("myBinaryFile.bin"), StandardOpenOption.READ));
fc.position(64);
fc.read(indexField);
System.out.println(indexField.getInt());
}
}
这是我得到的错误:
run:
Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.Buffer.nextGetIndex(Buffer.java:509)
at java.nio.HeapByteBuffer.getInt(HeapByteBuffer.java:373)
at testbinaryfile2.TestBinaryFile2.main(TestBinaryFile2.java:30)
/home/user/.cache/netbeans/11.3/executor-snippets/run.xml:111: The following error occurred while executing this line:
/home/user/.cache/netbeans/11.3/executor-snippets/run.xml:94: Java returned: 1
BUILD FAILED (total time: 0 seconds)
1条答案
按热度按时间cczfrluj1#
读取后,索引字段指向其末端,因此有必要使用
.rewind()
方法获取int。此代码适用于:
此外,我还建议使用Map缓冲区:
但我想知道
fc.map
一次读取整个文件并使用与文件大小相同的内存。