简体   繁体   English

从二进制文件中读取特定字节

[英]Read a specific byte from binary file

I am trying to figure out how to get to a specific byte in a binary file using java. 我试图弄清楚如何使用java获取二进制文件中的特定字节。 I've done a ton of reading on byte level operations and have gotten myself thoroughly confused. 我已经对字节级操作进行了大量阅读,并让自己彻底搞砸了。 Right now I can loop through a file, as in the code below, and tell it to stop at the byte I want. 现在我可以遍历文件,如下面的代码所示,并告诉它停在我想要的字节。 But I know that this is ham-fisted and there is a 'right' way to do this. 但是我知道这是吝啬的,并且有一种'正确'的方式来做到这一点。

So for example if I have a file and I need to return the byte from off-set 000400 how can I a get this from a FileInputStream? 所以例如,如果我有一个文件,我需要从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++;
        }
    }

Thanks 谢谢

You need RandomAccessFile for the job. 你需要RandomAccessFile来完成这项工作。 You can set the offset by the seek() method. 您可以通过seek()方法设置偏移量。

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

You can use the skip() method of FileInputStream to "skip n bytes". 您可以使用FileInputStream的skip()方法来“跳过n个字节”。

Though be aware that: 虽然要注意:

The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0. 由于各种原因,跳过方法可能最终跳过一些较小数量的字节,可能是0。

It returns the actual number of bytes skipped, so you should check it with something like: 它返回跳过的实际字节数,因此您应该检查以下内容:

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

使用RandomAccessFile - 请参阅此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM