Reputation: 31
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?
Upvotes: 1
Views: 175
Reputation: 178263
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
Upvotes: 1
Reputation: 183301
I see two issues here:
seek
-ing between your last write and your first read, so you're starting your reads after the end of where you last wrote. (The fact that you're not immediately getting EOFException
indicates that your file was not empty at the beginning of this program run.)seek
takes an argument representing a byte position, but writeInt
and readInt
write and read four bytes. So if you don't want your integers to overlap each other, you'll need to seek to positions 0, 4, 8, etc., instead of 0, 1, 2, etc. (Though as it happens, you don't actually need your current calls to seek
if your goal is for the integers to be adjacent.)Upvotes: 0