【发布时间】:2023-03-27 15:46:01
【问题描述】:
我想将对象的数组列表存储在一个文件中,以便在再次打开应用程序后访问它们。
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();
}
此代码不起作用 - 我的意思是当我保存完整的数组列表并终止应用程序时,当我在打开应用程序时尝试再次读取它时它什么也不返回。这里有什么问题?
【问题讨论】:
标签: android file serialization