Java - Lectura secuencial de un RandomAccessFile?

 
Vista:
sin imagen de perfil

Lectura secuencial de un RandomAccessFile?

Publicado por Jaime (4 intervenciones) el 15/10/2017 22:38:41
Hola:
Necesito ayuda con una escritura/lectura de un RandomAccessFile mediante entorno gráfico de Java.

Adjunto código de escritura:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
RandomAccessFile file;
String clave = grabarRegistro_clave.getText();
String nombre = grabarRegistro_nombre.getText();
int edad = Integer.parseInt(grabarRegistro_edad.getText());
double sueldo = Double.parseDouble(grabarRegistro_sueldo.getText());
try{
   file = new RandomAccessFile(new File("datos.dat"),"rw");
   long fileSize = file.length();
   file.seek(fileSize);
   file.writeUTF(clave);
   file.writeUTF(nombre);
   file.writeInt(edad);
   file.writeDouble(sueldo);
 
 
   file.close();
}catch(IOException io){
   io.getStackTrace();
}

Y código de lectura:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int pos = 0;
String nombre = null;
String clave = null;
int edad = 0;
double sueldo = 0;
 
try{
    RandomAccessFile raf = new RandomAccessFile("datos.dat","r");
    long tamano = raf.length();
    raf.seek(0);
 
    while(raf.getFilePointer()<tamano){
        clave = raf.readUTF();
        nombre = raf.readUTF();
        edad = raf.readInt();
        sueldo = raf.readDouble();
        resultadosRegistros.setText("Clave: "+clave+" Nombre: "+nombre+" Edad: "+edad+" Sueldo: "+sueldo);
 
    }
    raf.close();
}catch(IOException e){
    System.out.println("Error");
}

El código de escritura está correcto, puesto que abro el archivo y puedo comprobar que me está insertando todos los datos que le meto, pero a la hora de leer los datos introducidos en ese archivo solo me muestra el último que meto, y no todos los ya existentes.
Si alguien me podría orientar... Gracias.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder