Java之序列化和反序列化

序列化的对象:

 package test_demo.SerializableOper;

 import java.io.Serializable;
/*
* 序列化对象需要实现序列号接口
* */
public class Book implements Serializable {
// 指定序列化的jdk版本
// private static final long serialVersionUID =1L;
String name;
int price; public Book(String name, int price) {
this.name = name;
this.price = price;
} public String toString() {
return "name: " + name + ", price: " + price;
}
}

序列化和反序列化操作代码:

 package test_demo.SerializableOper;

 import java.io.*;

 /*
* 序列化和反序列化举例
* 序列化:把对象保存在硬盘的过程
* 序列化的对象需要实现序列化接口
* */
public class SerializableOper {
public static void main(String args[]) throws IOException, ClassNotFoundException {
Book book = new Book("阿甘正传", 55);
System.out.println(book);
String filePath = "C:\\testdata\\s\\book.txt"; // 序列化
FileOutputStream fos = new FileOutputStream(filePath);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(book);
oos.close();
fos.close(); // 反序列化
FileInputStream fis = new FileInputStream(filePath);
ObjectInputStream ois = new ObjectInputStream(fis);
Book b = (Book) ois.readObject();
System.out.println(b); }
}

book对象序列化后保存在C:\testdata\s\book.txt中。

上一篇:java之序列化


下一篇:Java IO 学习总结 学习手册总结