GARA
博闻强记 多思多问 取法乎上 持之以恒
  1. 存在背景 :在内存中可以创建可复用的Java对象,,但是会随着JVM的停止儿消失,但是在部分场景中,JVM停止后需要保存指定的对象,Java对象序列化满足了这一需求
  2. 实现过程

  • 实体类实现 Serializable接口 
public class User implements Serializable
  • ObjectInputStream写入对象
    //write object into file
    ObjectOutputStream oos = null;       try{ oos = new ObjectOutputStream(new FileOutputStream("tempfile")); oos.writeObject(user); }catch (Exception e){ e.printStackTrace(); }finally { IOUtils.closeQuietly(oos); }

 

  • ObjectOutputStream 读取对象
    //read object from file
        File file = new File("tempFile");
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(file));
            User newUser = (User) ois.readObject();
            System.out.println(newUser);
        }catch (IOException e){
            e.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(ois);
            try {
                FileUtils.forceDelete(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

  

 

posted on 2018-07-31 17:34  GaraYing  阅读(114)  评论(0编辑  收藏  举报