【发布时间】:2018-07-29 02:27:07
【问题描述】:
我有一个可序列化的对象数据。当我的主要活动加载时,我希望它检查存储中是否有保存的数据实例。如果是这样,读取它并实例化为变量。如果没有,将使用新的数据副本。
我的对象读写代码:
// Method used to read questions data
public static void read(){
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream("SAVED_DATA");
in = new ObjectInputStream(fis);
myData = (Data) in.readObject();
in.close();;
} catch(Exception e){
e.printStackTrace();;
}
}
// Method used to write the questions data
public static void save(){
FileOutputStream fos = null;
ObjectOutputStream out = null;
try{
fos = new FileOutputStream("SAVED_DATA");
out = new ObjectOutputStream(fos);
out.writeObject(myData);
} catch (Exception e){
e.printStackTrace();
}
}
我的 onCreate() 方法中的代码类似于:
if (read()) { //How to test if a Data object exists?
read(); // Read the object from storage and set variable to the result
} else {
myData = new Data(); // There's no stored object so set up a new one
}
最好(最简单)的方法是什么?
【问题讨论】:
标签: java android storage serializable