Java基础之对象的序列化(持久化)操作对象ObjectInputStream/ObjectOutputStream

本文展示了一个使用Java进行对象序列化和反序列化的简单示例。通过将Person类的对象写入文件并从文件中读取,演示了如何利用ObjectOutputStream和ObjectInputStream实现这一过程。
import java.io.*;

class ObjectInputStreamDemo
{
    public static void main(String[] args) throws Exception
    {    
        String fileName = "obj.txt";
        writer(fileName,new Person("陈晓明",28));
        Person person = reader(fileName);
        
        System.out.println(person.toString());
    }
    
    public static Person reader(String fileName) throws Exception
    {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(fileName)));
        Person person = (Person)ois.readObject();        
        ois.close();
        
        return person;
    }
    
    public static void writer(String fileName,Person person)  throws Exception
    {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(fileName)));
        oos.writeObject(person);        
        oos.close();
    }
}

class Person implements Serializable
{
    public static final long serialVersionUID = 42L;

    String name;
    int age;
    
    public Person(String name,int age)
    {
        this.name = name;
        this.age = age;
    }
    
    public String toString()
    {
        return (this.name + "::" + this.age);
    }
}

转载于:https://www.cnblogs.com/cxmsky/archive/2013/02/02/2889766.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值