·序列化类:java.io.ObjectOutputStream,将对象变为了指定格式的二进制数据;
·反序列化类:java.io.ObjectOutputStream,可以将序列化的对象转换回对象内容;
实现序列化操作-ObjectOutputStream
·构造方法:public ObjectOutputStream(OutputStream out)throws Exception
·输出对象:public final writeObject(Object obj)throws Exception;
范例:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
@SuppressWarnings("serial")
class Book implements Serializable {
private String tiltle;
private double price;
public Book(String title, double price) {
this.tiltle = title;
this.price = price;
}
@Override
public String toString() {
return "书名《" + this.tiltle + "》,价格:" + this.price + "元。";
}
}
public class Demo {
public static void main(String[] args) throws Exception {// 此处直接抛错
ser();
//dser();
}
// 序列化
public static void ser() throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(new File("e:" + File.separator + "book.ser")));
oos.writeObject(new Book("Java从入门到精通", 88.8));
oos.close();
}
// 反序列化
public static void dser() throws Exception {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(new File("e:" + File.separator + "book.ser")));
Object obj = ois.readObject();
Book book = (Book) obj;
System.out.println(book);
ois.close();
}
}
序列化结果:
反序列化结果: