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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…