揭开Java序列化的神秘面纱 Serializable使用详解
    		       		warning:
    		            这篇文章距离上次修改已过451天,其中的内容可能已经有所变动。
    		        
        		                
                Java序列化提供了一个简单的对象保存到文件或数据库的方式,以便于保存对象的状态。在Java中,一个类实现了Serializable接口,就可以被序列化。
下面是一个简单的例子,展示如何将一个对象序列化到文件并从文件中反序列化回对象:
import java.io.*;
 
public class Main {
    public static void main(String[] args) {
        // 创建一个示例对象
        ExampleObject obj = new ExampleObject(1, "示例字符串");
 
        // 序列化对象到文件
        try {
            FileOutputStream fos = new FileOutputStream("example.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(obj);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        // 反序列化对象从文件
        try {
            FileInputStream fis = new FileInputStream("example.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            ExampleObject objRead = (ExampleObject) ois.readObject();
            ois.close();
 
            // 输出反序列化得到的对象的属性
            System.out.println("id: " + objRead.id);
            System.out.println("name: " + objRead.name);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
 
// 这个类需要实现Serializable接口以支持序列化
class ExampleObject implements Serializable {
    int id;
    String name;
 
    public ExampleObject(int id, String name) {
        this.id = id;
        this.name = name;
    }
}在这个例子中,ExampleObject类实现了Serializable接口,以便可以被序列化。然后,我们创建了一个ExampleObject对象并序列化到文件example.ser。之后,我们从文件中反序列化对象,并打印出它的属性。
这只是序列化和反序列化的基本使用方法,实际使用时可能需要处理更复杂的情况,比如多个版本的兼容性问题,或者自定义序列化过程以优化性能。
评论已关闭