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.