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