我想在文件中存储对象的arraylist,以便在再次打开应用后与他们联系。
public class SmsMessage implements Serializable {
public static enum MessageType {
Sent,
Received;
};
private String body;
private Date date;
private MessageType type;
public SmsMessage(String _body, Date _date, MessageType _type) {
body = _body;
date = _date;
type = _type;
}
}
那是整个班级。我是这样保存的:
FileOutputStream fout = null;
ObjectOutputStream out = null;
try {
fout = context.getApplicationContext()
.openFileOutput(FILENAME, Context.MODE_PRIVATE);
out = new ObjectOutputStream(fout);
out.writeObject(list);
out.close();
} catch (IOException ioe) {
System.out.println("Error in save method");
} finally {
out.close();
fout.close();
}
并按如下方式阅读:
ObjectInputStream in = null;
FileInputStream fis = null;
try {
fis = context.getApplicationContext().openFileInput(FILENAME);
in = new ObjectInputStream(fis);
ArrayList<SmsMessage> list = null;
list = (ArrayList<SmsMessage>)in.readObject();
} catch (Exception ex) {
System.out.println("Error in get method");
} finally {
in.close();
fis.close();
}
这段代码不起作用 - 我的意思是当我保存完整的arraylist并杀死应用程序时,当我在打开应用程序时再次尝试读取它时,它什么都不会返回。这有什么不对?
答案 0 :(得分:0)
初始化如下:
fout=new FileOutputStream(FILENAME));
在out.writeObject(list)之后;添加此行
out.flush();
类似初始化
fis = new FileInputStream((FILENAME));
希望这有效....你在logcat上收到任何错误信息吗?