ObjectOutputStream
package zuoye;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Demo14 {
public static void main(String[] args) throws IOException {
//序列化与反序列化
Book b = new Book("金苹果","讲述了种植过程");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c://book.hahas"));
oos.writeObject(b);
oos.close();
}
//序列化需要实现Serializable接口
static class Book implements Serializable {
private String name;
private String info;
public Book(String name, String info) {
this.name = name;
this.info = info;
}
public Book() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", info='" + info + '\'' +
'}';
}
}
}
注意:序列化需要实现Serializable接口,并且类内所有其他类属性都要实现。
ObjectInputStream
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c://book.hahas"));
oos.readObject(b);
oos.close();
新发现
HashMap存储时,需要放入一个类中进行,HashMap不支持序列化,并且新创建的类要开启追加模式,不然还是会报错!