我试图弄清楚如何使用java获取二进制文件中的特定字节.我已经对字节级操作进行了大量阅读,并让自己彻底搞砸了.现在我可以遍历文件,如下面的代码所示,并告诉它停在我想要的字节.但是我知道这是吝啬的,并且有一种'正确'的方式来做到这一点.
所以例如,如果我有一个文件,我需要从off-set 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++;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
Bal*_*usC 12
你需要RandomAccessFile这份工作.您可以通过seek()方法设置偏移量.
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(400); // Goes to 400th byte.
// ...
Run Code Online (Sandbox Code Playgroud)