Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
859 views
in Technique[技术] by (71.8m points)

java - How do I fetch specific bytes from a file knowing the offset and length?

I have a file, and the first 4 bytes of the file are the magic such as LOL . How would I be able to get this data?

I imagined it would be like:

byte[] magic = new byte[4];
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.read(magic, 0, magic.length);
System.out.println(new String(magic));

Output:

LOL

Sadly this isn't working for me. I can't find a way to fetch specific values.

Does anyone see any way to solve this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use RandomAccessFile.seek() to position to where you want to read from and RandomAccessFile.readFully() to read a full byte array.

byte[] magic = new byte[4];
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0L);
raf.readFully(magic);
System.out.println(new String(magic));

The problem with your code is that when you create the file in read-write mode, most likely the file pointer points to the end of the file. Use the seek() method to position.

Also you can use the RandomAccessFile.read(byte[] b, int off, int len) method too, but the offset and length corresponds to the offset in the array where to start storing the read bytes, and length specifies how many bytes to read from the file. But the data will still be read from the current position of the file, not from the off position.

So once you called seek(0L);, this read method also works:

raf.read(magic, 0, magic.length);

Also note that the read and write methods will automatically move the current position, so for example seeking to 0L, then reading 4 bytes (your magic word) will result in the current pointer being moved to 4L. This means you can call read methods subsequently without having to seek before each read and they will read a continuous portion of the file increasing by position, they will not read from the same position.

Last Note:

When creating a String from a byte array, quoting from the javadoc of String(byte[] bytes):

Constructs a new String by decoding the specified array of bytes using the platform's default charset.

So the platform's default charset will be used which may be different on different platforms. Always specify a correct encoding like this:

new String(magic, StandardCharsets.UTF_8);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...