IO_序列化

>>>>>>>>>>

说明:学生类对象

package IO;

import java.io.Serializable;

/**
 * 需要序列化的学生类
 * @author Dawn
 *
 */
public class Student implements Serializable {
    private String name;
    private String sex;
    private int age;
    
    public Student(){
        super();
    }
    
    public Student(String name, String sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    
}

>>>>>>>>>>

说明:序列化与反序列化

package IO;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**实现序列化的测试类
 * @author 潇洒hongtu 
 *
 */
public class xuliehua {
public static void main(String[] args) {
    /*序列化 (输出流)*/
    output();
    /*反序列化(输入流)*/
    input();
}
/**
 * 序列化
 */
public static void output(){
    try {
        /*第一步 打开管道和打开处理流*/
        FileOutputStream out = new FileOutputStream("C:\a.txt");
        ObjectOutputStream oot = new ObjectOutputStream(out);
        /*第二步 实例化需要序列化的对象*/
        Student s = new Student("大哥哥","男",38);
        /*第三步 将对象往文档中写出*/
        oot.writeObject(s);
        /*第四步 刷新*/
        oot.flush();
        /*第五步 关闭流*/
        oot.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    
}/*output*/

/**
 * 反序列化(输入流)
 */
public static void input(){
    try {
        /*第一步 打开2种流*/
        FileInputStream in = new FileInputStream("C:\a.txt");
        ObjectInputStream oin = new ObjectInputStream(in);
        /*第二步 将文档中的对象读取进来*/
        Student stu = (Student)oin.readObject();
        System.out.print(stu.getName()+"
"+stu.getAge()+"	"+stu.getSex());
        oin.close();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    
}
}

>>>>>>>>>>

原文地址:https://www.cnblogs.com/xuehx/p/6422982.html