JAVA 对象输入流不能从循环中退出



这是我的代码:

    ObjectInputStream ois = null;
    UserRegistration UR = new UserRegistration();

    Scanner pause = new Scanner(System.in);
    Admin go = new Admin();
    try {
        //ItemEntry book = new ItemEntry();
        ois = new ObjectInputStream(new FileInputStream("Account.txt"));
        while ((UR = (UserRegistration) ois.readObject()) != null) {
            //if (book.getName().equals("1"))
            {
                System.out.println(UR);
            }
        }
    } catch (EOFException e) {
       System.out.println("nEnd**");
    }catch (ClassNotFoundException ex) {
        System.out.println(ex.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            ois.close();
            System.out.println("Press "ENTER" to continue...");
            pause.nextLine();
            go.startup();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

如何让它从循环中退出,而不是在到达最后一个对象时直接进入 EOFException?请帮忙!

这是这个问题的重复:

Java FileInputStream ObjectInputStream 到达文件 EOF 的末尾

底线是 ObjectInputStream 在到达流的末尾时不会返回 null。相反,底层 FileInputStream 会抛出一个 EOFException。尽管您可以将其解释为文件的结尾,但它不允许您区分截断的文件。因此,实际上,ObjectInputStream希望您知道将读取多少对象。

要解决此问题,您可以在文件的开头写入一个整数,指示文件中有多少 UserRegistration 对象。读取该值,然后使用 for 循环读取这么多对象。

或者,您可以将 UserRegister 对象序列化为数组或其他容器,然后反序列化整个数组/容器。

最新更新