2012-03-10 230 views
2

我正在java中制作一个小程序,并且我希望它从二进制文件中的设置位置读取。就像文件流中的子字符串一样。任何好的方法来做到这一点?从二进制文件(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(); 
+0

RandomAccessFile的可能是你想要的东西:HTTP: //docs.oracle.com/javase/6/docs/api/java/io/RandomAccessFile.html – 2012-03-10 16:46:02

+0

[在Java/Android中读取文件的一部分]的可能的重复(http://stackoverflow.com/questions/ 3581243 /阅读java中的一段文件的安卓) – 2012-03-10 16:49:46

+0

感谢那就是我一直在寻找:) – user952725 2012-03-13 19:22:02

回答

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