Java教程

Java 序列化

本文主要是介绍Java 序列化,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package 序列化;

import java.io.*;

public class 序列化 {
    public static void main(String[] args) throws Exception {
        对象序列化();
        反序列化();
    }

    //一次序列化要对应一次反序列化
    private static void 反序列化() throws Exception {
        String out = "D:\\API.txt";
        ObjectInputStream OIS = new ObjectInputStream(new FileInputStream(out));
        Object o = OIS.readObject();
        System.out.println(o);
        OIS.close();
    }

    private static void 对象序列化() throws Exception {
        String out = "D:\\API.txt";
        Stu stu = new Stu("QianL", 12);
        ObjectOutputStream OOS = new ObjectOutputStream(new FileOutputStream(out));
        //OOS.writeObject(OOS);
        OOS.writeObject(stu);
        OOS.close();
        System.out.println("序列化成功");
    }
}

//序列化必须 implements  Serializable
class Stu implements Serializable {
    //以下代码固定代码序列号
    //private static final long serialVersionUID = 1L;
    public String name;
    public int age;

    public Stu(String Name, int Age) {
        name = Name;
        age = Age;
    }

    @Override
    public String toString() {
        return "Stu{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

这篇关于Java 序列化的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!