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).
这篇博客讨论了如何在Java中正确读取二进制文件中的所有内容,特别是当文件包含多个序列化对象时。作者指出,将序列化对象简单地拼接在一个文件中是不好的做法,建议使用集合来存储。如果无法修改生成文件的代码,解决方案包括知道对象的数量并进行相应次数的`readObject()`调用,或者使用循环和异常处理来检测文件结束。
1661

被折叠的 条评论
为什么被折叠?



