Java序列化与反序列化

序列化是将对象转换为可保持或传输格式的过程,反序列化是将流转化成对象。
代码如下

import java.io.Serializable;
public class Person implements Serializable{
    private static final long serialVersionUID = 1L;
        private String name;
        private int age;
        public Person(){        
        }
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public int getAge() {
            return age;
        }
}

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeToFile {
    private ObjectInputStream ois;
    public static void main(String args[]) {
        SerializeToFile  stf = new SerializeToFile();
        stf.savePerson();
        stf.restorePerson();
    }
    public void savePerson() {
        Person myPerson = new Person("Jack",19);
        try {
            FileOutputStream fileout = new FileOutputStream("E:\\myPerson.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fileout);
            oos.writeObject(myPerson);          
            oos.flush();
            oos.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    public void restorePerson() {
        try {
            FileInputStream fis = new FileInputStream("E:\\myPerson.txt");
            ois = new ObjectInputStream(fis);  
            Person myPerson = (Person)ois.readObject();
            System.out.println("Name is: "+myPerson.getName());
            System.out.println("Age is: "+myPerson.getAge());
        } catch (Exception e) {
           e.printStackTrace();
        }
    }
}

其中savePerson()方法将myPerson对象序列化到文本myPerson.txt中,而restorePerson()方法将流文本反序列化成对象myPerson

运行结果为:
Name is: Jack
Age is: 19

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值