DataInputStream does not read full file

0

With this code I add new users to a binary file, list all existing ones and allows to search for one in particular and show all the data associated with it:

case 1: System.out.println("Introduce nombre: ");
        nombre=teclado.next();
        System.out.println("Introduce apellido: ");
        apellido=teclado.next();
        System.out.println("Introduce año de nacimiento: ");
        nacido=teclado.nextInt();
        dos.writeUTF(nombre);
        dos.writeUTF(apellido);
        dos.writeInt(nacido);
        break;
case 2: try {
            FileInputStream fis=new FileInputStream("file.bin");
            DataInputStream dis=new DataInputStream(fis);
            while (dis.available()>0) {
                   System.out.println(dis.readUTF()+" "+dis.readUTF()+" nació en "+dis.readInt());
            }
            fis.close();
       }
       catch (EOFException e) {System.out.println("Fin del fichero.");}
       break;
case 3: System.out.println("Introduce el nombre a buscar: ");
        String buscar=teclado.next();
        try {
            FileInputStream fis=new FileInputStream("file.bin");
            DataInputStream dis=new DataInputStream(fis);
            while (dis.available()>0) {
                   if (buscar.compareTo(dis.readUTF())==0) {
                           System.out.println("Los datos completos del usuario son: "+dis.readUTF()+" "+dis.readUTF()+" que nació el "+dis.readInt());
                           break;
                   }
            }
            fis.close();
        }
        catch (EOFException e) {System.out.println("No se encontró el usuario.");}
        break;

Add user and list all work ok, however not so search. Why in case 2 the loop reads the complete file without problems and in the third one it only reads 1 or 2 data and the "no user found" issue already comes out?

Greetings.

    
asked by Stephan 07.05.2017 в 14:25
source

1 answer

1

The problem is that in the case 3 you are reading the name within the if and then to show the user data you reread it, this causes an exception since you use the dis.readInt() method in an incorrect order .

if (buscar.compareTo(dis.readUTF())==0) {
    System.out.println("Los datos completos del usuario son: "+dis.readUTF()+" "+dis.readUTF()+" que nació el "+dis.readInt());
     break;
}

To solve it, just:

while (dis.available() > 0) {
    String nombre = dis.readUTF();
    if (buscar.compareTo(nombre)==0) {
        System.out.println("Los datos completos del usuario son: " + nombre + " " + dis.readUTF() + " que nació el " + dis.readInt());
        break;
    }
    else{
        dis.readUTF();
        dis.readInt();
    }
}
    
answered by 07.05.2017 в 17:59