I have a file:
RandomAccessFile file = new RandomAccessFile("files/bank.txt", "r");
And I am reading and writing data to/from this file using:
for (int pos = 0; pos < 1000; pos++) {
file.seek(40 * pos + 30);
double money = file.readDouble();
if (pos == num) {
money += i;
System.out.println(money+" "+i);
file.seek(40 * pos + 30);
file.writeDouble(money);
}
}
In this way it reads the double - works correctly, and then it should overwrite that double with the value it held previously plus i
. However this is not working as the value doesn't change. What have I done wrong?
You have opened file only for reading:
RandomAccessFile("files/bank.txt", "r");
you should open it with:
new RandomAccessFile("files/bank.txt", "rws");
which opens for reading and writing, as with "rw", and also require that every update to the file's content or metadata be written synchronously to the underlying storage device.
or with:
new RandomAccessFile("files/bank.txt", "rwd");
which opens for reading and writing, as with "rw", and also require that every update to the file's content be written synchronously to the underlying storage device.