欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

对象序列化及反序列化

程序员文章站 2022-03-22 15:25:21
...
import java.io.*;

public class Demo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String filename = "file.dat";

        /**
         *  将对象写入文件
         */
        ObjectOutputStream obj = new ObjectOutputStream(
            new FileOutputStream(filename));

        Student s = new Student("boy", "James", 1);
        obj.writeObject(s);

        /**
         *  将对象读出文件
         */
        ObjectInputStream objIn = new ObjectInputStream(
            new FileInputStream(filename));
        Student std = (Student)objIn.readObject(); // 此处 readObject() 方法返回的是 Object 对象,必须强制转换
        System.out.println(std); // ID = 1 Name = James Sex = null
        
        objIn.close();
        obj.close();
    }
}

class Student implements Serializable { // 如果要将一个对象序列化,必须实现 Serializable
    private String name;
    private int id;
    private transient String sex; // transient 关键字表示该属性不可序列化
    public Student () {
        
    }
    public Student (String sex, String name, int id) {
        this.sex = sex;
        this.name = name;
        this.id = id;
    }
    public int getId() {
        return this.id;
    }
    public String getName() {
        return this.name;
    }
    public String getSex() {
        return this.sex;
    }

    @Override
    public String toString() {
        return ("ID = " + this.getId() + " " + "Name = " + 
        this.getName() + " " + "Sex = " + this.getSex()); 
    }
}

 

相关标签: Java