Read a specific byte from binary file

那年仲夏 提交于 2019-12-11 02:22:00

问题


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.

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

Thanks


回答1:


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.
// ...



回答2:


You can use the skip() method of FileInputStream to "skip n bytes".

Though be aware that:

The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 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) 
}



回答3:


Use a RandomAccessFile - see this question.



来源:https://stackoverflow.com/questions/11545039/read-a-specific-byte-from-binary-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!