对象序列化及反序列化_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 对象序列化及反序列化

对象序列化及反序列化

 2018/8/15 21:35:42  NOthingAj  程序员俱乐部  我要评论(0)
  • 摘要:importjava.io.*;publicclassDemo{publicstaticvoidmain(String[]args)throwsIOException,ClassNotFoundException{Stringfilename="file.dat";/***将对象写入文件*/ObjectOutputStreamobj=newObjectOutputStream(newFileOutputStream(filename));Students=newStudent("boy"
  • 标签:序列化 反序列化
class="java" name="code">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()); 
    }
}

?

发表评论
用户名: 匿名