序列化
序列化就是把实例的对象转换成字节的形式,方便在网络或者磁盘当中传递,并且保证数据的完整性。
序列化也就引出了反序列化,反序列化就是在磁盘当中读取出来数据并重新构造成对象,注意,序列化存在id。
序列化只需要实现Serializable接口或者Externalizable接口就可以
对象流ObjectInputStream/ObjectOutputStream
ObjectInputStream输入流可以把实例化的对象写入到本地文件当中,要写入的对象必须经过序列化。
ObjectOutputStream输出流可以把本地文件当中已经序列化的对象重新组装成对象,并且保持原有数据。
File file = new File("u.db");
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
//获取
List<Student> n= (List<Student>) ois.readObject();
System.out.println(n.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//写入
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file, true))) {
Student dad = new Student(20, "dad");
Student dad1 = new Student(30, "dad");
List<Student> ls=new ArrayList<>();
ls.add(dad);
ls.add(dad1);
oos.writeObject(ls);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @auto:Mrs.Y
* @email:2508108731@qq.com
*/
package com.wc.file.pojo;
import java.io.Serial;
import java.io.Serializable;
/**
*
**/
public class Student implements Serializable {
@Serial
private static final long serialVersionUID = 3513146177409139281L;
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Student(Integer id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
private Integer id;
private String name;
}