java二进制对象,从Java中的二进制文件读取序列化的对象?

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值