Search code examples
javaseekrandomaccessfile

Adding and reading integers to RandomAcessFile from a List. All except the last one seem to be "0"


I'm trying to write five random numbers from a List to a file. I think I'm managing to write something but when I try to read the file they are all 0 except the last one. I've searched but most of what I've found just explain how to write one int/string. I think the problem comes from how I am writing. writeInt writes as four bytes and maybe I'm not using seek() in accordance.

This is my code.

try {
        RandomAccessFile ficheroJugador1 = new RandomAccessFile("jugador1.dat", "rw");
        for (int i = 0; i < 5; i++) {
            try {
                ficheroJugador1.seek(i);
                int numEscribir = jugador1.numerosAleatorios.get(i);
                ficheroJugador1.writeInt(numEscribir);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        
        for (int i = 0; i < 5; i++) {
            try {
                ficheroJugador1.seek(i);
                try {
                    System.out.println(ficheroJugador1.readInt());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        try {
            ficheroJugador1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

This results in:

Numbers [10, 9, 3, 8, 7] //The numbers I want to write and read

0

0

0

0

7


Solution

  • As you said, by not using seek correctly you are overwriting the last saved number

    (ascii representation)
    0010
    ^
    00009
     ^
    000003
      ^
    000008
       ^
    00000007
        ^
    

    If you change ficheroJugador1.seek(i); to ficheroJugador1.seek(i*4); you will correctly give each number its space

    (ascii representation)
    00100009000300080007