DataInputStream 读取不正确?

DataInputStream isn't reading properly?

我对 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 个单词并且已经显示 "user not found",关于为什么的任何建议?

此致。

所以你的问题是你的 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 - 也不会显示任何消息 - 你也应该修复它。