public class test{
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:\\demo\\book.ser")));
oos.writeObject(new Book("haha",34.56));
oos.close();
}
public static void dser()throws Exception{//反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("E:\\demo\\book.ser")));
Object obj = ois.readObject();
Book book = (Book)obj;
System.out.println(book);
ois.close();
}
}
class Book implements Serializable{
private String title;
private double price;
public Book(String title,double price){
this.title = title;
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", price=" + price +
'}';
}
}
本文介绍了一个简单的Java程序,演示了如何使用Java内置的序列化接口将一个包含书籍信息的对象写入文件,以及如何从该文件中读取并还原这个对象。示例代码展示了序列化和反序列化的基本过程。

被折叠的 条评论
为什么被折叠?



