package test01;
import java.io.*;
public class serializableDemo
{
public static void main(String[] args) throws IOException, ClassNotFoundException {
//创建对象
Product product = new Product();
//给属性赋值
product.setPname("香香");
product.setPrice(1000);
product.setCategory_id("c008");
//文件对象
File file = new File("text.srs");
//文件输入流和输出流
FileOutputStream fileOutputStream = new FileOutputStream(file);
//对象流
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
//对象写入序列化
objectOutputStream.writeObject(product);
//测试读取序列流
FileInputStream fileInputStream = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
//向上专行
Product product2 = (Product)objectInputStream.readObject();
System.out.println(product2.getPname());
}
}
对象序列化
最新推荐文章于 2024-08-27 16:18:18 发布
这篇博客展示了如何在Java中实现对象的序列化和反序列化。通过创建一个`Product`对象,设置其属性,然后使用`FileOutputStream`、`ObjectOutputStream`进行序列化操作,将对象保存到文件。接着,使用`FileInputStream`和`ObjectInputStream`读取并反序列化文件,恢复对象,并打印出反序列化后的对象属性。
摘要由CSDN通过智能技术生成