【发布时间】:2017-03-25 23:19:08
【问题描述】:
如何将 ArrayList 保存到文件中? 我在做什么?ng?
我已经使用这个 SO 问题来帮助我处理可序列化的对象。:
how to serialize ArrayList on android
我使用了这个关于如何编写数组列表的问题:
Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?
但是,当我尝试将 写入文件时,我得到了错误:
java.io.NotSerializableException: 在
java.io.ObjectOutputStream.writeObject at
com.mycompany.MyClass.saveData
这是尝试保存文件的 MyClass
private ArrayList < MyCustomObject > arrayList;
private File dataFile;
private String FILE_NAME = "FILE_DATA.dat";
public void init(final Context context) {
this.appContext = context;
dataFile = new File(appContext.getFilesDir(), FILE_NAME);
if (dataFile.exists()) {
loadData();
} else {
try {
dataFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
arrayList = new ArrayList < MyCustomObject > ();
saveData();
}
}
private void saveData() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dataFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fos != null) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(fos);
if (oos != null) {
oos.writeObject(arrayList);
}
assert oos != null;
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void loadData() {
FileInputStream fis = null;
try {
fis = new FileInputStream(dataFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fis != null) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(fis);
if (ois != null) {
try {
arrayList = (ArrayList < MyCustomObject > ) ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
}
assert ois != null;
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这是我的自定义对象
public class MyCustomObject implements Serializable {
public String myname = "";
public String someOtherItem = "";
public int aNumber = 0;
public MyCustomObject getCustomObject() {
return this;
}
}
【问题讨论】:
-
您要序列化什么 -
MyClass实例的arrayList成员变量,还是MyClass实例本身? -
我想我应该序列化我的 ArrayList,因为那是需要保存的。
-
确实 -
MyClass似乎有一个Context成员(请参阅init方法中的this.appContext),这肯定是不可序列化的! -
既然 MyCustomObject 是可序列化的,那么 ArrayList
不也可以通过继承实现序列化吗?它实际上是一个可序列化对象的列表。 -
啊!好的,让我快速阅读。
标签: java android arraylist fileoutputstream objectoutputstream