bufferunderflowexception

sqougxex  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(384)

我试图读取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)
cczfrluj

cczfrluj1#

读取后,索引字段指向其末端,因此有必要使用 .rewind() 方法获取int。
此代码适用于:

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);
            indexField.rewind();    // <-- ADD THIS
            System.out.println(indexField.getInt());

    }

}

此外,我还建议使用Map缓冲区:

public static void main(String[] args) throws Exception {
    FileChannel fc = (FileChannel.open(Paths.get("myBinaryFile.bin"), StandardOpenOption.READ));
    MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    buffer.position(64);
    System.out.println(buffer.getInt());
  }

但我想知道 fc.map 一次读取整个文件并使用与文件大小相同的内存。

相关问题