Serializable
- 可串行化,可序列化,是一种标识接口,表示一种能力。
- 实现了该接口的类具有可序列化的能力。
- 一般对实体类实现可序列化
- 序列化:将对象转换为字节序列,便于数据的存储和网络传输
- 反序列化:将字节序列转化为对象
与之相关的类:
- 二进制流(继承自字节流)
DataInputStream, DataOutputStream
- 对象流(继承自字节流)
ObjectInputStream, ObjectOutputStream
序列化包装数据类型:
FileOutputStream fos = new FileOutputStream("string.txt");
DataOutputStream dos = new DataOutputStram(fos);
//String str = "hello world 你好 世界";
//dos.writeUTF(str);
Integer i = 12345;
dos.writeInt(i);
dos.close();
fos.close();
反序列化包装数据类型:
FileInputStream fis = new FileInputStream("string.txt");
DataInputString dis = new DataInputStream(fis);
//String str = dis,readUTF();
int i = dis,readInt()
dis.close();
fis.close();
序列化学生类型:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.txt"));
oos.writeObject(new Student("阿文", 28, '男'));
oos.close();
反序列化学生对象
ObjectInputStream ois = new ObejctInputStream(new FileInputStream("student.txt"));
Student student = (Student)ois.readObejct();
System.out.println(student);
ois.close();
序列化和反序列化集合
Arraylist<Student> list = new Arraylist<>();
list.add(new Student("A", 18, '女');
list.add(new Student("B", 20, '男');
list.add(new Student("C", 16, '女');
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt"));
oos.writeObject(list);
oos.close();
ObejctInput ois = new ObjectInputStream(new FileInputStream("list.txt"));
List<Student> list2 = (List<Student>)ois.readObject();
System.out.println(list2);
ois.close();
作业:
使用序列化反序列化实现数据的持久化