Using RandomAccessFile
class, I'm trying to test the concept of writing/reading to/from a file in java. So I tried this code:
public static void main (String[] args) throws IOException {
RandomAccessFile storage = new RandomAccessFile("FILE.txt", "rw");
storage.seek(0);
storage.writeInt(1);
storage.seek(1);
storage.writeInt(2);
storage.seek(2);
storage.writeInt(3);
storage.seek(3);
storage.writeInt(4);
storage.seek(4);
storage.writeInt(5);
System.out.println(storage.readInt());
System.out.println(storage.readInt());
System.out.println(storage.readInt());
System.out.println(storage.readInt());
System.out.println(storage.readInt());
storage.close();
I think it should print : 1 2 3 4 5
but what happens is that it prints: 3 4 5 EOFException... why?
There are 2 problems here - you are not allowing 4 bytes per int
written, and you are not seeking back to the start of the file when reading the int
s back into memory.
First, the seek
method takes an argument of the number of bytes as an offset into the file.
pos
- the offset position, measured in bytes from the beginning of the file, at which to set the file pointer.
But in Java int
s have 4 bytes, so you are overwriting 3 of the previous int
's 4 bytes with each subsequent write. Either explicitly set the mark to 4 bytes later each time:
storage.seek(4);
storage.writeInt(2);
storage.seek(8);
storage.writeInt(3);
// etc.
Or even easier, the mark "does the right thing" and moves forward the appropriate number of bytes. Just leave out the seek
s here.
storage.writeInt(1);
storage.writeInt(2);
storage.writeInt(3);
storage.writeInt(4);
storage.writeInt(5);
The second problem is that when reading the bytes back, you don't reset the mark back to the beginning of the file, causing an EOFException
. Add a call to seek(0)
to send the mark back to the beginning of the file.
storage.seek(0);
System.out.println(storage.readInt());
System.out.println(storage.readInt());
System.out.println(storage.readInt());
System.out.println(storage.readInt());
System.out.println(storage.readInt());
Then I get the output:
1
2
3
4
5