序列化和反序列化

来源:互联网 发布:软件设计师怎么考 编辑:程序博客网 时间:2024/06/05 19:19

序列化:把对象转化为字节序列的过程称为对象的序列化。

反序列化:把字节序列恢复为对象的过程称为对象的反序列化。

把数据跨域JVM生命周期保存下来。

package xulie;

import java.io.*;
import java.util.*;

public class Test {
    private static void write(List<Student> list) {
        File file = new File("E:\\乱七八糟\\text10.txt");
        // Student对象序列化过程
        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(new BufferedOutputStream(
                    new FileOutputStream(file)));
            out.writeObject(list);//把list写入文件
            out.flush();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    private static List<Student> read() {
        File file = new File("E:\\乱七八糟\\text10.txt");
        // Student对象反序列化过程
        ObjectInputStream input = null;
        List<Student> list = null;
        try {
            input = new ObjectInputStream(new BufferedInputStream(
                    new FileInputStream(file)));
            list = (List<Student>) input.readObject();
            for (Student li : list) {
                System.out.println(li.getName()+li.getSex());
            }
            input.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void main(String[] args) {
        List<Student> list = new ArrayList<Student>();
        Student st = new Student("Tom", 1);
        Student st2 = new Student("nana", 0);
        list = new ArrayList<Student>();
        list.add(st);
        list.add(st2);
        write(list);
        read();
    }

}

//实体类

package xulie;

import java.io.Serializable;
//Serializable接口是启用其序列化功能
public class Student implements Serializable {
    private String name;
    private int sex;
    public Student() {
    }
    public Student(String name, int sex) {
        this.name = name;
        this.sex = sex;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }

    
}

0 0