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

我的梦境 提交于 2019-12-18 08:58:21

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/26790224/how-do-i-fetch-specific-bytes-from-a-file-knowing-the-offset-and-length

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