首页 > 其他 > 详细

序列化和反序列化

时间:2021-04-19 01:56:21      阅读:34      评论:0      收藏:0      [点我收藏+]
public class SerilizableDemo {
public static void main(String[] args) {
serialize();
deserialize();
}

public static void serialize() {
try {
       //关键点,被序列化的对象类需要实现Serializable接口,否则会抛出不支持序列化异常
Myuser myuser = new Myuser();
myuser.setAge(12);
myuser.setName("wang");
FileOutputStream outputStream = new FileOutputStream("src/main/resources/Myuser");
//
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(myuser);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void deserialize() {
try {
FileInputStream fis = new FileInputStream("src/main/resources/Myuser");
ObjectInputStream objectInputStream = new ObjectInputStream(fis);
//
Myuser myuser = (Myuser)objectInputStream.readObject();
System.out.println(myuser);
} catch (Exception e) {
e.printStackTrace();
}
}
}

transient关键字:
public class Myuser implements Serializable {
private String name;

private int age;

  
  private transient String name; // 如果被transient修饰,序列化时就会忽略该字段


public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

序列化和反序列化

原文:https://www.cnblogs.com/dust-to-dust/p/14674868.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!