IO流丶序列化与反序列化

序列化就是利用ObjectOutputStream与FileOutputStream之间的联系将数据写入文本中;

反序列化是利用ObjectInputStream与FileInputStream之间的联系将数据读出来,已实体类的方式接受。

一个Student对象的序列化:

package liu;

import java.io.Serializable;

/**
 * 实体类pojo
 * Created by Administrator on 2017/9/1.
 */
public class Student implements Serializable {
    private static final long serializUID= -1888888888L;
    String name ;
    int id;
    transient int age;
    String department;
    public Student() {
    }
    public Student(String name, int id, int age, String department) {
        this.name = name;
        this.id = id;
        this.age = age;
        this.department = department;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", age=" + age +
                ", department='" + department + '\'' +
                '}';
    }
}
package liu;

import java.io.*;

/**
 * 序列化
 * Created by Administrator on 2017/9/1.
 */
public class StudentXLH {
    //对实体类进行序列化
    private static void SerializeStudent() throws Exception{
        Student s = new Student();
        s.name="马云";
        s.age=21;
        s.id=138;
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("aaa.txt")));//序列化信息放在文本中
        oos.writeObject(s);
        System.out.println("序列化成功!");
    }
    //反序列化为实体类
    private static void FanSerializeStudent() throws Exception{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("aaa.txt"));
        Student student = (Student) ois.readObject();
        System.out.println("姓名:"+student.name+",年龄:"+student.age);
    }
    public static void main(String[] args) throws  Exception{
        SerializeStudent();
        FanSerializeStudent();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值