Java序列化
序列化(ObjectOutputStream):将对象存储在文件内
反序列化(ObjectIntputStream):将对象从文件内读出来
- Book
import java.io.Serializable;
public class Book implements Serializable {
//transient 表示不持久化,即不序列化
private int id;
private String name;
private int money;
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
public Book(int id, String name, int money) {
this.id = id;
this.name = name;
this.money = money;
}
public Book() {
}
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 getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
- ObjectOutputStream
/**
* 序列化
*/
public class Test0907SaveBook {
public static void main(String[] args) throws IOException {
//创建Book对象,Book对象必须实现Serializable接口
Book book = new Book(1,"活着",20);
//创建FileOutputStream对象,指定文件,true表示可以追加内容
FileOutputStream fileOutputStream = new FileOutputStream("D:/Book.txt",true);
//创建ObjectOutputStream对象,输入FileOutputStream对象作为参数
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
//将对象写入文件(序列化)
objectOutputStream.writeObject(book);
//关闭字节流释放资源
objectOutputStream.close();
fileOutputStream.close();
System.out.println("序列化成功");
}
}
结果
- ObjectIntputStream
/**
* 反序列化
*/
public class Test0907DrawBook {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//创建FileInputStream对象,指定文件
FileInputStream fileInputStream =new FileInputStream("D:/Book.txt");
//创建ObjectInputStream对象,输入FileInputStream作为参数
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
//读取对象(反序列化)
Book book = (Book) objectInputStream.readObject();
System.out.println(book);
//关闭字节流释放资源
objectInputStream.close();
fileInputStream.close();
}
}
结果