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

I have a file, and the first 4 bytes of the file are magic like LOL

. How can I get this data?

I thought it would be like this:

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

Unfortunately this doesn't work for me. I cannot find a way to get specific values.

Does anyone see any way to solve this problem?

+3


source to share


1 answer


Use RandomAccessFile.seek()

to indicate where you want to read and RandomAccessFile.readFully()

to read the complete array byte

.

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 a file in read-write mode, most likely the file pointer is pointing to the end of the file. Use the seek()

placement method .

You can also use the method RandomAccessFile.read(byte[] b, int off, int len)

, but the offset and length correspond to the offset in the array where to start storing the bytes read, and length determines the number of bytes to read from the file. But the data will still be read from the current file position , not from the position off

.

So, once you've called seek(0L);

, this read method also works:

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

      



Also note that the read and write methods automatically move the current position, so for example aiming at 0L

, then reading 4 bytes (your magic word) will move the current pointer to 4L

. This means that you can subsequently call the read methods without having to search before each read, and they will read a contiguous portion of the file, incrementing in position, they will not read from the same position.

One final note:

When created String

from an array byte

, quoting from the javadoc String(byte[] bytes)

:

Creates a new string decoding the specified byte array using the platform default encoding .

Thus, the default platform encoding will be used, which may differ on different platforms. Always indicate correct coding as follows:

new String(magic, StandardCharsets.UTF_8);

      

+5


source







All Articles