Java 如何序列化对象的 ArrayList 并将其保存到文件(在 android 中)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19742103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:51:42  来源:igfitidea点击:

How do I serialize an ArrayList of objects and save it to a file (in android)?

javaandroidserializationarraylistsave

提问by abc32112

This is probably really simple, but after having read a number of guides, I can't figure out what's wrong with my code. The following is supposed to serialize and save a list of objects contained in an ArrayList. It works, exceptall instance variables contained in the objects in the ArrayList, are lost.

这可能真的很简单,但是在阅读了许多指南之后,我无法弄清楚我的代码有什么问题。下面应该序列化并保存包含在 ArrayList 中的对象列表。它可以工作,除了ArrayList 中的对象中包含的所有实例变量都丢失了。

Edit: can someone tell me if this part of the code is correct?

编辑:有人能告诉我这部分代码是否正确吗?

try {
        FileOutputStream fos = this.openFileOutput ( FILENAME, Context.MODE_PRIVATE );
        ObjectOutputStream oos = new ObjectOutputStream ( fos );
        oos.writeObject ( arrayList );
        oos.close ();
    } catch ( Exception ex ) {
        ex.printStackTrace ();
    }

回答by Sipka

First you should check the Logcat output whether writing, or reading fails.

首先,您应该检查 Logcat 输出是否写入或读取失败。

You are using oos.writeObject(arrayList); Make sure that the items of arrayList are implementing the Serializable interface, else the writing will fail. For example:

您正在使用 oos.writeObject(arrayList); 确保 arrayList 的项正在实现 Serializable 接口,否则写入将失败。例如:

public class MyClass implements Serializable { }
...
ArrayList<MyClass> arrayList = new ArrayList<MyClass>();
/*add items*/
oos.writeObject(arrayList);//it will not throw Exception, because MyClass implements Serializable

and reading with (ArrayList<MyClass>) ois.readObject();but you know that.

和阅读,(ArrayList<MyClass>) ois.readObject();但你知道。