2017-10-18 45 views
0

这里辍学是我的代码有:JAVA的ObjectInputStream不能从环

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类,当它到达的最后一个对象?请帮助 !

+0

在没有任何异常之前,您不会进入catch块。 – Russiancold

+0

为什么您需要退出循环?也许有更好的方法来完成你想要的东西。 –

+0

我试过添加异常,但输出仍然保持不变。我不能在while循环之后做任何动作,导致它直接进入EOFException。 –

回答

1

这是这个问题的一个副本:

Java FileInputStream ObjectInputStream reaches end of file EOF

底线是,当它到达流的末尾ObjectInputStream中没有返回null。相反,基础FileInputStream抛出一个EOFException。虽然您可以将其解释为文件的结尾,但它不允许您区分截断的文件。因此,实际而言,ObjectInputStream的希望你知道有多少对象,你会被读取。

要解决这个问题,你可以到文件的开头表明许多放在userRegistration对象如何在文件中的整数。读取该值,然后使用for循环读取多个对象。

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

相关问题