Java - Random Access File

 
Vista:
sin imagen de perfil

Random Access File

Publicado por Wrath (1 intervención) el 02/04/2014 07:52:15
Saludos. Estoy iniciando en los archivos de acceso aleatorio y tengo un pequeño problema en un ejercicio, lo que pasa es que al imprimir la información del archivo.dat en un jTextArea me presenta algo como !@#$$# 0 y 0.0. Si alguien puede ayudarme de antemano gracias.

INGRESO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int cantidad = 1;
cantidad += cb_cant.getSelectedIndex();
double precio = Double.parseDouble(cb_precio.getText());
String cod = tf_cod.getText();
String des = tf_des.getText();
String prov = tf_pro.getText();
if(cod.length() < 10)
    for(int i = cod.length(); i < 10; i++)
        cod += "."; // completar los 10 caracteres
if(des.length() < 15)
    for(int i = des.length(); i < 15; i++)
        des += "."; // completar los 15 caracteres
if(prov.length() < 10)
    for(int i = prov.length(); i < 10; i++)
        prov += "."; // completar los 10 caracteres
try{
    RandomAccessFile ventas = new RandomAccessFile("productos.dat","rw");
    ventas.writeChars(cod + des + prov);
    ventas.writeInt(cantidad);
    ventas.writeDouble(precio);
    ventas.close();
}
catch(FileNotFoundException e){
    System.out.println(e.getMessage());
}
catch(IOException e){
    System.out.println(e.getMessage());
}



LECTURA por codigo del registros

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
String codigo = tf_cod.getText();
char cod[] = new char [10];
char des[] = new char [15];
char prov[] = new char [10];
int cant = 0;
double precio = 0;
try {
    RandomAccessFile archivo = new RandomAccessFile("productos.dat","r");
    archivo.seek(0); //nos situamos al principio
    for(int i = 0; i < archivo.length(); i += 82){
        for(int j = 0; j < 10; j ++)
            cod[j] = archivo.readChar();
        if(tfcod.getText().equals(cod)){
            archivo.seek(i);
        for(int k = 0; k < 10; k ++)
            cod[k] = archivo.readChar();
        archivo.skipBytes(20);
        for(int l = 0; l < 15; l ++)
            des[l] = archivo.readChar();
        archivo.skipBytes(50);
        for(int m = 0; m < 10; m ++)
            prov[m] = archivo.readChar();
        archivo.skipBytes(70);
        cant = archivo.readInt();
        archivo.skipBytes(74);
        precio = archivo.readDouble();
        }
        archivo.close();
        ta_ consulta.append(cod + "\n" + des + "\n" + prov + "\n" + cant + "\n" + precio);
    }
} catch (FileNotFoundException e) {
    System.out.println("Fin de fichero");
} catch (IOException ex) {
    System.out.println(ex.getMessage());
}
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
sin imagen de perfil

Random Access File

Publicado por Iván (3 intervenciones) el 02/04/2014 19:41:17
Hola.
He modificado tu código fuente. No lo he probado al 100% pero creo que te funcionará sin mucho problema.

Ese error que te da, si mal no me equivoco, es porque intentas leer un tipo de dato diferente al que hay en la posición sobre la que te encuentras en el fichero. O bien puede ser porque no lees el datos desde su posición inicial, sino que a partir de una posterior.

Espero que te sirva.
Saludos.

INGRESO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
int cantidad = 1;
cantidad += cb_cant.getSelectedIndex();
double precio = Double.parseDouble(cb_precio.getText());
String cod = tf_cod.getText();
String des = tf_des.getText();
String prov = tf_pro.getText();
 
//Ya no es necesario rellenar los strings para que todos los registros tengan el mismo tamaño
//if(cod.length() < 10)
//   for(int i = cod.length(); i < 10; i++)
//      cod += "."; // completar los 10 caracteres
//
//if(des.length() < 15)
//   for(int i = des.length(); i < 15; i++)
//      des += "."; // completar los 15 caracteres
//
//if(prov.length() < 10)
//   for(int i = prov.length(); i < 10; i++)
//      prov += "."; // completar los 10 caracteres
 
try{
   RandomAccessFile ventas = new RandomAccessFile("productos.dat","rw");
   ventas.writeUTF(cod); //Personalmente prefiero usar writeUTF() para escribir strings
   ventas.writeUTF(des);
   ventas.writeUTF(prov);
   ventas.writeInt(cantidad);
   ventas.writeDouble(precio);
   ventas.close();
}
catch(FileNotFoundException e){
   System.out.println(e.getMessage());
}
catch(IOException e){
   System.out.println(e.getMessage());
}



LECTURA por codigo del registros
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
String cod, des, prov;
int cant = 0;
double precio = 0;
 
try {
   RandomAccessFile archivo = new RandomAccessFile("productos.dat","r");
 
   //No hace falta usar archivo.seek(0)  dado que al empezar a leer se situa en cero por defecto
 
   boolean coinciden = false;// Para cuando uno de los registros del archivo coincida con el tfcod
 
   do{
      //No hace falta usar seek() dado que cada vez que se lee algo se mueve el puntero al final del último dato
      cod = archivo.readUTF();
      des = archivo.readUTF();
      prov = archivo.readUTF();
      cant = archivo.readInt();
      precio = archivo.readDouble();
 
      if(tfcod.getText().equals(cod))
        coinciden = true;
 
   }while(!coinciden & archivo.getFilePointer() < archivo.length()); //Mientras no coincidan y no sea el fin del fichero
 
   archivo.close();
   ta_consulta.append(cod + "\n" + des + "\n" + prov + "\n" + cant + "\n" + precio);
}
} catch (FileNotFoundException e) {
   System.out.println("Fin de fichero");
} catch (IOException ex) {
   System.out.println(ex.getMessage());
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar