你的位置:首页 > Java教程

[Java教程][javaSE] IO流(对象序列化)


写入

获取ObjectOutputStream对象,new出来,构造参数:FileOutputStream对象目标文件

调用ObjectOutputStream对象的writeObject()方法,参数:要保存的对象

调用ObjectOutputStream对象的close()方法,关闭流

 

此时会报异常,NotSerialzeableException,是因为目标类没有实现Serializable接口,这个接口没有方法,称为标记接口,会在改变类之后,生成新的序列号,保存的文件读取时会显示错误信息InvalidClassException

 

读取

获取ObjectInputStream对象,new出来,构造参数:FileInputStream对象目标文件

调用ObjectInputStream对象的readObject()方法,得到保存的数据

 

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;public class ObjectStreamDemo {  /**   * @param args   * @throws Exception   */  public static void main(String[] args) throws Exception {    writeObj();    readObj();  }  /**   * 保存对象   * @throws IOException   * @throws FileNotFoundException   */  public static void writeObj() throws Exception{    ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("person.object"));    oos.writeObject(new Person("taoshihan",100));  }    public static void readObj() throws Exception{    ObjectInputStream ois=new ObjectInputStream(new FileInputStream("person.object"));    Person person=(Person) ois.readObject();    System.out.println(person);//输出 taoshihan:100  }}/** * 自定义的类 * @author taoshihan * */class Person implements Serializable{  private String name;  private int age;  public Person(String name,int age) {    this.name=name;    this.age=age;  }  @Override  public String toString() {    // TODO Auto-generated method stub    return name+":"+age;  }}

 

PHP版:

<?phpclass Person{  private $name;  private $age;  public function __construct($name,$age){    $this->name=$name;    $this->age=$age;  }  public function toString(){    return $this->name.":".$this->age;  }}$personObj=serialize(new Person("taoshihan",100));echo $personObj;// 输出 O:6:"Person":2:{s:12:"Personname";s:9:"taoshihan";s:11:"Personage";i:100;}$obj=unserialize($personObj);echo $obj->toString();//输出 taoshihan:100