使用Person类作为Object进行示范
注意:Object要能被写入流需要实现Serializable接口
存储的文件后缀名为.ser
示范Person类
import java.io.Serializable;
public class Person implements Serializable{ private static final long serialVersionUID = 1L; String name; int age; boolean sex;//true means male false means female Person(String name,int age,boolean sex) { this.name=name; this.age=age; this.sex=sex; } void print() { System.out.println("姓名:"+name); System.out.println("年纪:"+age); System.out.println("性别:"+sex); } }
将Person对象序列化存储到文件
示范Serializable_Test 类
import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream;
public class Serializable_Test {
public static void main(String[] args) { try { Person p=new Person("张三",18,true); File f=new File("D:\\objecttest.ser"); FileOutputStream fos=new FileOutputStream(f); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(p); oos.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } }
从文件中读取对象,反序列化Deserializable
示范Deserializable_Test类
import java.io.File; import java.io.FileInputStream; import java.io.ObjectInputStream;
public class Deserializable_Test {
public static void main(String[] args) { try { File f=new File("d:\\objecttest.ser"); FileInputStream fis=new FileInputStream(f); ObjectInputStream ois=new ObjectInputStream(fis); Person p=(Person)ois.readObject(); p.print(); } catch (Exception e) { e.printStackTrace(); } } }