DataInputStream读取不正确?

时间:2017-05-07 14:01:54

标签: java datainputstream

我对Java编程和新手都很陌生。堆栈溢出,今天早上我一直在跟随简单的代码遇到大麻烦。它有3个选项,将新用户添加到二进制文件中,列出每个用户,并搜索特定用户以显示与其相关的所有其他数据(姓氏和年份):

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("user not found.");}
        break;

添加用户&列出他们都工作正常,但搜索选项不是。 如果2个循环正在读取整个文件,虽然在案例3中它只读1-2个单词并且已经显示“用户未找到”,对于为什么有任何建议?

问候。

1 个答案:

答案 0 :(得分:1)

所以你的问题是当文件意外结束时会打印出你的user not found消息。

这意味着当没有其他内容可供阅读时,您尝试从文件中读取。

问题在于这段代码:

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;
                   }

在这里,您阅读一次进行比较,然后尝试再次阅读以便打印出来(这就是问题)。

您需要做的是仅读取每个字段一次 - 如果您想再次使用它(例如打印),则将其值分配给变量。

所以,这样的事情应该有效:

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

*顺便说一句,在你的实现中 - 很有可能找不到用户 - 但是因为没有抛出Exception - 也不会显示任何消息 - 你也应该修复它。