[Java 12 IO] Serializable 初步 ObjectOutputStream ObjectInputStream 将序列化的对象打出来...

Person 类, 序列化后就代表对象可以作为二进制的数据流进行传输
package com.qunar.basicJava.javase.io.serializable;

import java.io.Serializable;

/**
 * Author: libin.chen@qunar.com  Date: 14-6-6 10:21
 */
public class Person implements Serializable {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "姓名 : " + this.name + "; 年龄 : " + this.age;

    }
}
ObjectOutputStream 将序列化后的对象写入到文件中
package com.qunar.basicJava.javase.io.serializable;

import java.io.*;

/**
 * Author: libin.chen@qunar.com  Date: 14-6-6 10:25
 */
public class SerDemo01 {
    public static void main(String[] args) throws IOException {
        File file = new File("/home/hp/tmp/test.txt");
        ObjectOutputStream objectOutputStream = null;
        OutputStream outputStream = new FileOutputStream(file);
        objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(new Person("张三", 30));
        outputStream.close();

    }
}
 ObjectInputStream 将序列化的对象传回来
package com.qunar.basicJava.javase.io.serializable;

import java.io.*;

/**
 * Author: libin.chen@qunar.com  Date: 14-6-6 10:27
 */
public class SerDemo02 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        File file = new File("/home/hp/tmp/test.txt");
        ObjectInputStream objectInputStream = null;
        InputStream inputStream = new FileInputStream(file);
        objectInputStream = new ObjectInputStream(inputStream);
        Object object = objectInputStream.readObject();
        objectInputStream.close();
        System.out.println(object);

    }
}


转载于:https://www.cnblogs.com/robbychan/p/3786488.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值