从Java中的二进制文件读取序列化的对象? [英] Reading serialized objects from a binary file in java?
问题描述
如何读取java中二进制文件的所有内容?
我写了一些代码,检索第一个对象。
这是我的代码:
pre $ Object $ 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();
- )或者你知道对象的数量,那么你可以做正确数量的
ObjectInputStream.readObject()
调用,最好使用作为
循环 - ,否则,问题是检测到文件。你可以使用
,而
循环加上try / catch(EOFException)
。
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 afor
loop - or you don't, then the problem is detecting the end of the file. You could use a
while
loop coupled with atry/catch(EOFException)
.
这篇关于从Java中的二进制文件读取序列化的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!