【发布时间】:2017-10-18 16:12:49
【问题描述】:
这是我的代码:
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?请帮忙!
【问题讨论】:
-
在没有异常之前不会进入catch块
-
为什么需要退出循环?也许有更好的方法来完成你正在尝试的事情。
-
我尝试添加异常,但输出仍然保持不变。在while循环之后我不能做任何动作,导致它直接进入EOFException。
-
ois.available();应该会有所帮助。我不确定它是否适用于ObjectInputStream。否则,您可以考虑在文件的统计信息处写一个int,指示有多少对象,然后读取该数字。第二种选择更安全。
标签: java objectinputstream eofexception