对象的序列化

package com.zhu.io;
import java.io.*;

/**
 * Created by idea on 2016/6/6.
 * @我就是你们的小星星
 *
 * 对象的序列化和反序列化
 */
public class ObjectStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String srcPath = "d:/testio/a.txt";
        String descPath = "d:/testio/a.txt";
        outStream(srcPath);
        readStream(descPath);
    }
    //反序列化
    public static void readStream(String srcPath) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(srcPath)));
        Person person1 = (Person) ois.readObject();
        Person person2 = (Person) ois.readObject();
        System.out.println(person1.getName());
        System.out.println(person2.getName());
    }
    //序列化
    public static void outStream(String descPath) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(descPath)));
        oos.writeObject(new Person("竹洪鑫" , 18 , 1 , 500 ));
        oos.writeObject(new Person("田启瑞" , 19 , 2 , 600));
    }

}

package com.zhu.io;
import java.io.Serializable;

/**
 * Created by idea on 2016/6/6.
 * @我就是你们的小星星
 *
 * 实体类(必须实现serialzable的类才能被序列化,这个接口只是个空接口;
 * 被transient标记的属性将不会被序列化)
 */
public class Person implements Serializable{

    private String name;
    private int age;
    private transient int id ;
    private int salary;

    public Person() {
    }

    public Person(String name, int age, int id, int salary) {

        this.name = name;
        this.age = age;
        this.id = id;
        this.salary = salary;
    }

    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 int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值