简体   繁体   中英

Reading serialized objects from a binary file in java?

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

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM