Reading serialized objects from a binary file in j

2019-03-07 06:52发布

问题:

I have a simple question.

How to read all the contents of the binary file in java ?

I wrote some code but it only retrieves the first object.

Here is my code:

    ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\Users\\فاطمة\\Downloads\\student.bin"));
    Binary b2 = (Binary)in.readObject();
    System.out.println("Student ID: " + b2.id);
    System.out.println("Student Name: " + b2.name);
    System.out.println("Student Grade: " + b2.grade);
    in.close();

回答1:

As malinator mentionned, it is bad practice to concatenate serialized objects in a single file, they should be contained in a Collection.

If you do not have access to the code producing the file, there can be 2 situations :

  • either you know the number of objects, then you can do the right number of ObjectInputStream.readObject() calls, preferably with a for loop
  • or you don't, then the problem is detecting the end of the file. You could use a while loop coupled with a try/catch(EOFException).