您的位置:首页 > 移动开发 > Objective-C

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

2013-02-02 09:19 796 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐