Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

You have the file open for reading only:

RandomAccessFile file = new RandomAccessFile("files/bank.txt", "r");

Change that line to:

RandomAccessFile file = new RandomAccessFile("files/bank.txt", "rw");

And you will be able to update with the code you have above. :)

This is a classic debug error, you should've breakpointed at money += i to see the value change, the document not changing is another issue and should have been addressed as the possibility of the file not being writable. i.e. you should've opened for writing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top