[javaSE] IO流(对象序列化)
发布时间:2021-05-21 06:44:49 所属栏目:大数据 来源: https://www.jb51.cc
导读:写入 获取 ObjectOutputStream 对象, new 出来,构造参数: FileOutputStream 对象目标文件 调用 ObjectOutputStream 对象的 writeObject() 方法,参数:要保存的对象 调用 ObjectOutputStream 对象的 close() 方法,关闭流 ? 此时会报异常, NotSerialzeab
写入 获取ObjectOutputStream对象,new出来,构造参数:FileOutputStream对象目标文件 调用ObjectOutputStream对象的writeObject()方法,参数:要保存的对象 调用ObjectOutputStream对象的close()方法,关闭流 ? 此时会报异常,NotSerialzeableException,是因为目标类没有实现Serializable接口,这个接口没有方法,称为标记接口,会在改变类之后,生成新的序列号,保存的文件读取时会显示错误信息InvalidClassException ? 读取 获取ObjectInputStream对象,new出来,构造参数:FileInputStream对象目标文件 调用ObjectInputStream对象的readObject()方法,得到保存的数据 ? import java.io.FileInputStream; java.io.FileNotFoundException; java.io.FileOutputStream; java.io.IOException; java.io.ObjectInputStream; java.io.ObjectOutputStream; java.io.Serializable; public class ObjectStreamDemo { /** * @param args * @throws Exception */ static void main(String[] args) throws Exception { writeObj(); readObj(); } * 保存对象 * IOException * FileNotFoundException void writeObj() Exception{ ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("person.object")); oos.writeObject(new Person("taoshihan",100)); } void readObj() 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, age) { this.name=name; this.age=age; } @Override public String toString() { TODO Auto-generated method stub return name+":"+age; } } ? PHP版: <?PHP Person{ private $name; $agefunction __construct($name,){ $this->name=; $this->age=; } function toString(){ return $this->name.":".$this->age; } } $personObj=serialize()); echo $personObj; 输出 O:6:"Person":2:{s:12:"Personname";s:9:"taoshihan";s:11:"Personage";i:100;} $obj=unserialize($personObj); $obj->toString();输出 taoshihan:100 ? (编辑:北几岛) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |