在 Android 上跨会话从文件写入然后读取 ArrayList<Object>?
Write and then read ArrayList<Object> from file across sessions on Android?
您好,我正在尝试在调用 onPause() and/or onStop() 时将对象的 ArrayList 保存到文件中,然后在应用程序被终止并重新启动后从该文件中读取 arrayList。我尝试了很多不同的方法,但 none 似乎有效,目前这就是我所拥有的。
我要编写的代码:
try{
FileOutputStream fout = openFileOutput(FILENAME, 0);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(toDos);
oos.close();
}
catch (Exception e){
e.printStackTrace();
}
我要阅读的代码:
try{
FileInputStream streamIn = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(streamIn);
if(ois.readObject() != null) {
list = (ArrayList<Object>) ois.readObject();
ois.close();
}
}
catch (Exception e){
e.printStackTrace();
}
"FILENAME" 是一个保存字符串 "data.txt" 的变量
toDos是arrayList的名字,它是Activity顶部的一个字段,它是一个可序列化的对象Object的ArrayList。
不确定我在这里做错了什么,我不知道它是否在写,或者问题可能出在哪里。
您收到 EOFException,因为您在对象中读取了 两次;一次检查 if 语句时,再一次在 if 语句中。将您的代码更改为如下内容:
FileInputStream streamIn = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(streamIn);
ToDoObject tmp = (ArrayList<ToDoObject>) ois.readObject();
ois.close();
if(tmp != null) {
toDos = tmp;
}
此代码完成相同的事情,但只从文件中读取一次。
您好,我正在尝试在调用 onPause() and/or onStop() 时将对象的 ArrayList 保存到文件中,然后在应用程序被终止并重新启动后从该文件中读取 arrayList。我尝试了很多不同的方法,但 none 似乎有效,目前这就是我所拥有的。
我要编写的代码:
try{
FileOutputStream fout = openFileOutput(FILENAME, 0);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(toDos);
oos.close();
}
catch (Exception e){
e.printStackTrace();
}
我要阅读的代码:
try{
FileInputStream streamIn = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(streamIn);
if(ois.readObject() != null) {
list = (ArrayList<Object>) ois.readObject();
ois.close();
}
}
catch (Exception e){
e.printStackTrace();
}
"FILENAME" 是一个保存字符串 "data.txt" 的变量 toDos是arrayList的名字,它是Activity顶部的一个字段,它是一个可序列化的对象Object的ArrayList。
不确定我在这里做错了什么,我不知道它是否在写,或者问题可能出在哪里。
您收到 EOFException,因为您在对象中读取了 两次;一次检查 if 语句时,再一次在 if 语句中。将您的代码更改为如下内容:
FileInputStream streamIn = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(streamIn);
ToDoObject tmp = (ArrayList<ToDoObject>) ois.readObject();
ois.close();
if(tmp != null) {
toDos = tmp;
}
此代码完成相同的事情,但只从文件中读取一次。