序列化
通过流传输写出对象就是序列化
1、序列化对象
private static void writeObj() {
Student201222 lg = new Student201222("lg", 21, 20);
try (FileOutputStream outputStream = new FileOutputStream("D://object.bin");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
objectOutputStream.writeObject(lg);
} catch (IOException e) {
e.printStackTrace();
}
}
序列化集合
private static void writeArr() {
List<Student201222> list = new ArrayList<>();
Student201222 lg = new Student201222("lg", 21, 20);
Student201222 ly = new Student201222("ly", 22, 9);
list.add(ly);
list.add(lg);
try (FileOutputStream outputStream = new FileOutputStream("D://object.bin");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
objectOutputStream.writeObject(list);
} catch (IOException e) {
e.printStackTrace();
}
}
反序列化
通过流传输读取对象就是反序列化
1、反序列化对象
private static void readObj() {
try (FileInputStream inputStream = new FileInputStream("D://object.bin");
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
Student201222 lg = (Student201222) objectInputStream.readObject();
System.out.println(lg.toString());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
2、反序列化集合
private static void readArr() {
try (FileInputStream inputStream = new FileInputStream("D://object.bin");
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
List<Student201222> list = (ArrayList) objectInputStream.readObject();
for (Student201222 student : list) {
System.out.println(student.toString());
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
总结
/**
* 序列化注意事项:
* 1、序列化必须要实现Serializable接口
* 2、序列化的类中的对象属性也必须实现Serializable接口
* 3、序列化版本号serialVersionUID,保证序列化的类和反序列化的类是统一个类
* 4、使用transient(瞬间的、瞬态)修饰的属性不能被序列化
* 5、static修饰的属性不能被序列化
* 6、序列多个对象,可用借助集合实现
*/