如何将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!

这是我将对象写入文件的代码:
MyClassList是一个arraylist,它包含我的类的对象(必须写入文件)。

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));
}

我在输出流的构造函数中添加了true,因为我想要将每个对象添加到文件末尾。这是正确的吗?

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

当然,假设MyClassList是一个 ArrayList LinkedList ,或其他 Serializable 集合。

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.