javaobjectinputstreameofexception

JAVA objectinputstream cant drop out from the loop


Here is the code I have:

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

How can I make it drop out from the loop and not to straight enter to the EOFException when it reach the last object? Help please !


Solution

  • This is a duplicate of this question :

    Java FileInputStream ObjectInputStream reaches end of file EOF

    Bottom line is that ObjectInputStream does not return null when it reaches the end of the stream. Instead, the underlying FileInputStream throws an EOFException. Although you could interpret that as the end of file, it does not allow you to distinguish a truncated file. So, practically speaking, ObjectInputStream expects you to know how many objects you will be reading in.

    To get around this you could write an integer to the start of the file indicating how many UserRegistration objects are in the file. Read that value, then use a for loop to read that many objects.

    Alternatively, you may be able to serialize your UserRegistration objects as an array or other container and then de-serialize the whole array/container.