1.定义
序列化:Serialize,java对象存储到文件中将java对象的状态保存下来的过程。
反序列化:DeSerialize,将硬盘上的数据重新恢复到内存当中,恢复成java对象。
2.实现序列化和反序列化
1.参与序列化和反序列的对象必须实现Serializable接口
2.Serializable接口是一个标志接口,起到标志作用,没有任何方法
3.Serializable这个标志接口是给java虚拟机参考的,java虚拟机看到这个接口之后,会为该类自动生成一个序列化版本号
3.transient
transient关键字表示不参加序列化
序列化的实现
public class ObjectOutputStreamTest {
public static void main(String[] args) {
User user = new User("tom",11);
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("students"));
oos.writeObject(user);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (oos != null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class User implements Serializable {
private String name;
private int age;
public User(){}
public User(String name, int age){
this.age = age;
this.name = name;
}
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;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
反序列化的实现
public class ObjectInputStreamTest {
public static void main(String[] args) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("students"));
Object o = ois.readObject();
System.out.println(o);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
在控制台输出
User{name='tom', age=11}
序列化多个对象
public class ObjectOutputStreamTest02 {
public static void main(String[] args) throws IOException {
List<User> users =new ArrayList<User>();
users.add(new User("tom",11));
users.add(new User("lbj",37));
users.add(new User("gurry",32));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user"));
oos.writeObject(users);
oos.flush();
oos.close();
}
}
public class ObjectInputStreamTest02 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user"));
Object o = ois.readObject();
System.out.println(o);
ois.close();
}
}
控制台输出
[User{name='tom', age=11}, User{name='lbj', age=37}, User{name='gurry', age=32}]
在属性前加入关键字transient
private transient String name;
控制台输出
[User{name='null', age=11}, User{name='null', age=37}, User{name='null', age=32}]