Reading serialized objects from a binary file in java?

与世无争的帅哥 提交于 2019-12-02 23:43:27

问题


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


来源:https://stackoverflow.com/questions/33923911/reading-serialized-objects-from-a-binary-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!