本文介绍了从二进制文件中读取特定字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何使用java获取二进制文件中的特定字节。我已经对字节级操作进行了大量阅读,并让自己彻底混淆了。现在我可以遍历文件,如下面的代码所示,并告诉它停在我想要的字节。但我知道这是一种吝啬的方式,并且有一种正确的方式来做到这一点。

I am trying to figure out how to get to a specific byte in a binary file using 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.

因此,例如,如果我有一个文件,并且我需要从off-set 000400返回该字节,我怎么能从FileInputStream中获取它?

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?

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++;
        }
    }

谢谢

推荐答案

你需要。您可以通过方法。

You need RandomAccessFile for the job. You can set the offset by the seek() method.

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

这篇关于从二进制文件中读取特定字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 13:23
查看更多