java 对象 序列化 文件中,如何将java序列化对象写入和读取到文件中

I am going to write multiple objects to a file and then retrieve them in another part of my code. My code has no error, but it is not working properly. Could you please help me find what is wrong about my code.

I have read different codes from different website, but none of them worked for me!

Here is my code to write my objects to a file:

MyClassList is an arraylist which includes objects of my class (which must be written to a file).

for (int cnt = 0; cnt < MyClassList.size(); cnt++) {

FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);

ObjectOutputStream oos = new ObjectOutputStream(fout);

oos.writeObject(MyClassList.get(cnt));

}

I added "true" to the constructor of the outputstream, because I want to add each object to end of file. Is that correct?

And here is my code to read the objects from the file:

try {

streamIn = new FileInputStream("G:\\address.ser");

ObjectInputStream objectinputstream = new ObjectInputStream(streamIn);

MyClass readCase = (MyClass) objectinputstream.readObject();

recordList.add(readCase);

System.out.println(recordList.get(i));

} catch (Exception e) {

e.printStackTrace();

}

It finally prints just one object. Now, I don't know if I am not writing correctly or reading correctly!

解决方案

Why not serialize the whole list at once?

FileOutputStream fout = new FileOutputStream("G:\\address.ser");

ObjectOutputStream oos = new ObjectOutputStream(fout);

oos.writeObject(MyClassList);

Assuming, of course, that MyClassList is an ArrayList or LinkedList, or another Serializable collection.

In the case of reading it back, in your code you ready only one item, there is no loop to gather all the item written.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值