首页 > 其他 > 详细

Serializable序列化输入输出练习

时间:2020-06-01 15:45:26      阅读:33      评论:0      收藏:0      [点我收藏+]

首先先创造一个Student对象类同时实现序列化接口

import java.io.Serializable;

public class Student implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    String name;
    int age;
    String sex;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Student(String name, int age, String sex) {
        super();
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", sex=" + sex + "]";
    }

}

然后写一个测试类

public class SerializableTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //method1();
        method2();
    }

    private static void method2() {
        // TODO 读文件并反序列化成对象
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:\\1.txt"));
            Object o = in.readObject();
            System.out.println(o.toString());
            in.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static void method1() {
        // TODO 对象序列化并输出到文件
        try {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\\1.txt"));
            Student stu = new Student("杨磊",11,"男");
            
            out.writeObject(stu);
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

}

method1输出到文件,method2从文件读取并反序列化成对象

从文件读取的结果

Student [name=杨磊, age=11, sex=男]

 

Serializable序列化输入输出练习

原文:https://www.cnblogs.com/cnbk/p/13025233.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!