目录
1.序列化的概念
一个Java对象作一个"变换",即Java对象换成字节序列,可以方便持久化储存到磁盘中,以避免程序运行结束后对象从内存中消失,另外字节序列更便于网络传输和传播。
反序列化:将字节序列变成Java对象。
2.序列化的具体实现
3.实现Car对象的属性的输入输出
报红:表示输入输出时,序列化是必须在实体中实现的。
import java.io.Serializable;
public class Car implements Serializable{
private String brand;
private Double price;
private String color;
public Car() { }
public Car(String brand, Double price, String color) {
this.brand = brand;
this.price = price;
this.color = color;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + ", color=" + color + "]";
}
}
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
/**
* 将Car的信息写入D:\car.dat
*/
public class OutputStream {
public static void main(String[] args) throws Exception {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\\car.dat"));
Car c = new Car("吉利", 899999.00, "白色");
out.writeObject(c);
out.close();
}
}
import java.io.FileInputStream;
import java.io.ObjectInputStream;
/**
* 将Car的信息读出
*/
public class InputStream {
public static void main(String[] args) throws Exception {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:\\car.dat"));
Car car = (Car)in.readObject();
System.out.println(car);
}
}
执行结果如下图所示: