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?
Use
RandomAccessFile.seek()
to position to where you want to read from andRandomAccessFile.readFully()
to read a fullbyte
array.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 theoff
position.So once you called
seek(0L);
, this read method also works: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 to4L
. 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 abyte
array, quoting from the javadoc ofString(byte[] bytes)
:So the platform's default charset will be used which may be different on different platforms. Always specify a correct encoding like this: