0

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 !

Russiancold
  • 1,179
  • 1
  • 11
  • 26
Huat Lee
  • 27
  • 2
  • You won't get into the catch block till there is no exception – Russiancold Oct 18 '17 at 16:16
  • Why do you need to drop out of the loop? Maybe there's a better way to accomplish what you're trying. – Karl Reid Oct 18 '17 at 16:19
  • I tried add Exception but the output still remain the same. I cant do any move after the while loop cause it straight go to EOFException. – Huat Lee Oct 18 '17 at 16:20
  • `ois.available();` should help. I'm unsure if it is implemented for `ObjectInputStream`. Otherwise, you could consider writing an `int` at the stat of the file indicating how many objects there are, then reading that number. The second option is far safer. – Obicere Oct 18 '17 at 16:37

1 Answers1

1

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.