Java序列化与反序列化

  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();
            }
        }

  

原文地址:https://www.cnblogs.com/gara/p/9397191.html