问题
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