从二进制文件中设置位置读取(Java)

3

我正在用Java编写一个小程序,希望它能从二进制文件的特定位置读取数据。就像在字符串中截取子字符串一样,只是这里需要在文件流上操作。有什么好的方法可以做到吗?

byte[] buffer = new byte[1024];   
FileInputStream in = new FileInputStream("test.bin");    
while (bytesRead != -1) {      
    int bytesRead = inn.read(buffer, 0 , buffer.length); 
} 
in.close();

RandomAccessFile 可能是你想要的:http://docs.oracle.com/javase/6/docs/api/java/io/RandomAccessFile.html - Ryan Amos
3个回答

3

一种实现此目的的方法是使用 java.io.RandomAccessFile 和它的 java.nio.FileChannel 从/向文件读取和/或写入数据,例如:

File file;  // initialize somewhere
ByteBuffer buffer;  // initialize somewhere
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel fc = raf.getChannel();
fc.position(pos);  // position to the byte you want to start reading
fc.read(buffer);  // read data into buffer
byte[] data = buffer.array();

1

对于上述问题,我会使用RandomAcessFile。

如果您正在加载大量数据,则应使用内存映射,因为它看起来要快得多(有时确实如此)。顺便说一下,您也可以使用FileInputStream进行内存映射。

FileChannel in = new FileInputStream("test.bin").getChannel();
MappedByteBuffer mbb = in.map(FileChannel.MapMode, 0, (int) in.size());
// access mbb anywhere
long l = mbb.getLong(40000000); // long at byte 40,000,000
// 
in.close();

1

如果你想做这件事,就必须知道你在哪里。 - Ryan Amos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接