Android系统是基于Linux,可使并发读写同一文件来交换数据。
序列化和反序列化代码如下
序列化 组件中写入如下方法
private void persisToFile(){
new Thread(new Runnable() {
@Override
public void run() {
User user = new User();
File dir = new File("./saved.cache");
if (!dir.exists())
dir.mkdir();
File cachedFile = new File("./saved.cache");
ObjectOutputStream objectOutput = null;
try{
objectOutput = new ObjectOutputStream(new FileOutputStream(cachedFile));
objectOutput.writeObject(user);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
反序列化组件中写入
private void recoverFromFile(){
new Thread(new Runnable() {
@Override
public void run() {
MainActivity.User user = null;
File cachedFile = new File("./saved.cache");
if (cachedFile.exists()){
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(new FileInputStream(cachedFile));
user = (MainActivity.User)objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}).start();
}