文件共享方式对文件格式没有要求
/**
* 文件共享
*/
//A类中 写入文件中
private void persistToFile() {
new Thread(new Runnable() {
@Override
public void run() {
User user = new User(1, "hello", false);
File cachedFile = new File("目录名");
ObjectOutputStream objectOutputStream = null;
try{
objectOutputStream = new ObjectOutputStream(new FileOutputStream(cachedFile));
objectOutputStream.writeObject(user);
}catch (Exception e) {
e.printStackTrace();
}finally {
MyUtils.close(objectOutputStream);
}
}
}).start();
}
//类B中 读取文件内容
private void recoverFromFile() {
new Thread(new Runnable() {
@Override
public void run() {
User user = null;
File cachedFile = new File("目录名");//同A目录名
if (cachedFile.exists()) {
ObjectInputStream objectInputStream = null;
try{
objectInputStream = new ObjectInputStream(new FileInputStream(cachedFile));
user = (User)objectInputStream.readObject();
}catch (Exception e){
e.printStackTrace();
}finally {
MyUtil.close(objectInputStream);
}
}
}
}).start();
}
![](https://i-blog.csdnimg.cn/blog_migrate/9143d1a8759d963d7412576322c88092.png)