Java序列化就是指把Java对象转换为字节序列的过程
Java反序列化就是指把字节序列恢复为Java对象的过程。
序列化最重要的作用:在传递和保存对象时,保证对象的完整性和可传递性。对象转换为有序字节流,以便在网络上传输或者保存在本地文件中。
反序列化的最重要的作用:根据字节流中保存的对象状态及描述信息,通过反序列化重建对象。
核心作用就是对象状态的保存和重建,整个过程核心点就是字节流中所保存的对象状态及描述信息。
下面我们写一个java程序实现java的序列化,反序列表。
public class BookA1 implements Serializable {
public static final long serialVersionUID = -6245370267703631160L;
private int id;
private String name;
private int price;
public BookA1(int id, String name, int price) {
this.id = id;
this.name = name;
this.price = price;
}
public void BookA1() {
}
@Override
public String toString() {
return "BookA1{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
在存储的时候一定要实现序列化,只需要将implements Serializable加在类后面。
在项目中也可以加入UID号
public static void main(String[] args) {
BookA1 book = new BookA1(1, "Java", 84);
List<BookA1> list = new ArrayList<>();
list.add(book);
try (var os = new ObjectOutputStream(new FileOutputStream("H:\\book.db"))) {
os.writeObject(list);
} catch (Exception e) {
e.printStackTrace();
}
}
执行方法将java对象存贮文文件。
将文件转化为Java对象
public static void main(String[] args) {
try (var is = new ObjectInputStream(new FileInputStream("H:\\book.db"))) {
List<BookA1> list = (List<BookA1>) is.readObject();
System.out.println(list.size());
System.out.println(list.toString());
} catch (Exception e) {
e.printStackTrace();
}
}