2012-07-18 75 views
2

我想弄清楚如何到达使用java的二进制文件中的特定字节。我已经完成了大量关于字节级操作的阅读,并且让自己彻底感到困惑。现在我可以遍历一个文件,如下面的代码所示,并且告诉它停止在我想要的字节处。但是我知道这是一种无聊的行为,而且有一种“正确”的方式来做到这一点。从二进制文件读取特定字节

因此,例如,如果我有一个文件,我需要从偏移000400返回字节我怎么能从FileInputStream得到这个?

public ByteLab() throws FileNotFoundException, IOException { 
     String s = "/Volumes/Staging/Imaging_Workflow/B.Needs_Metadata/M1126/M1126-0001.001"; 
     File file = new File(s); 
     FileInputStream in = new FileInputStream(file); 
     int read; 
     int count = 0; 
     while((read = in.read()) != -1){   
      System.out.println(Integer.toHexString(count) + ": " + Integer.toHexString(read) + "\t"); 
      count++; 
     } 
    } 

感谢

回答

10

需要RandomAccessFile作业。您可以通过seek()方法设置偏移量。

RandomAccessFile raf = new RandomAccessFile(file, "r"); 
raf.seek(400); // Goes to 400th byte. 
// ... 
2

您可以使用FileInputStream的skip()方法“跳过n个字节”。

虽然知道:

skip方法可以是,由于各种原因,最终超过 跳过的字节一些较小的数目,可能0

它返回实际字节数跳过,所以你应该喜欢的东西检查:

long skipped = in.skip(byteOffset); 
if(skipped < byteOffset){ 
    // Error (not enough bytes skipped) 
}