serialization 序列化
序列化 -> 将对象转化为字节序列的过程称为序列化
反序列化 -> 把字节序列恢复为对象的过程叫反序列化
使用地方
- 内存中的对象保存到一个文件或数据库中
- 用套接字(socket)在网络上传送对象的时候
- 想通过RMI传输对象的时候
package com.fallsown;
import java.io.*;
/**
* @author fallsown
* @date 2021/1/26 10:23
*/
public class Fallsown {
public static void main(String[] args){
Dog dog = new Dog();
try {
serializeDog();
dog = deserializeDog();
}catch (Exception e){
e.printStackTrace();
}
System.out.println(dog.toString());
}
/**
* 序列化
*/
private static void serializeDog() throws Exception{
Dog dog = new Dog();
dog.setWeight("58") ;
dog.setName("Wang Chai");
dog.setAddTip("is a dog");
ObjectOutputStream oss = new ObjectOutputStream(new FileOutputStream(new File("d:/dog.txt")));
try {
oss.writeObject(dog);
System.out.println("序列化成功");
oss.close();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 反序列化
*/
private static Dog deserializeDog() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("d:/dog.txt")));
Dog dog = new Dog();
try {
dog = (Dog) ois.readObject();
System.out.println("对象反序列化成功");
}catch (Exception e){
e.printStackTrace();
}
return dog;
}
}
package com.fallsown;
import java.io.Serializable;
/**
* @author fallsown
* @date 2021/1/26 10:15
*/
public class Dog implements Serializable {
private static String BREED = "369";
private String name;
private String weight;
transient private String car;
private String addTip;
public static String getBREED() {
return BREED;
}
public static void setBREED(String BREED) {
Dog.BREED = BREED;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getCar() {
return car;
}
public void setCar(String car) {
this.car = car;
}
public String getAddTip() {
return addTip;
}
public void setAddTip(String addTip) {
this.addTip = addTip;
}
@Override
public String toString(){
return "Dog{" +
"name='" + name + '\'' +
", weight='" + weight + '\'' +
", car='" + car + '\'' +
", BREED='" + BREED+ '\'' +
'}';
}
}
热水有益于身体健康