对象I/O
来自CloudWiki
对象序列化和反序列化
序列化和反序列化是一种用来处理对象流的机制,所谓对象流也就是将对象内容进行流化。可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。 存储对象的过程称为对象序列化,它是在ObjectOutputStream中实现的。与此相反,读取对象的过程称作对象反序列化,它是在ObjectOutputStream类中实现的。
图6-14 ObjectInputStream
图6-15 ObjectOutputStream
对象序列化和反序列化的实现
- 1.需要序列化的类实现Serializable接口,该接口没有需要实现的方法。implements Serializable只是为了标注该对象是可序列化的。
- 2.使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的WriteObject(Object obj)方法就可以将参数为obj的对象写出。(即保存其状态)。
- 3.要恢复的话则用输入流来构造一个ObjectInputStream对象。通过ObjectInputStream的readObject()把对象读入程序。
下面程序演示对象序列化:
(1)创建需要序列化的类Person.java。
public class Person implements Serializable{ private String name; private int age; public Person(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
(2)先将一个Person对象保存到文件person.txt中,然后再从该文件中读出被存储的Person对象,并打印该对象。
public class TestObjectInputStream { public static void main(String[] args) throws IOException, ClassNotFoundException { File file = new File("person.txt"); // 序列化持久化对象 ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file)); Person person = new Person("Peter", 27); out.writeObject(person); out.close(); // 反序列化,并得到对象 ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); Object newPerson = (Person) in.readObject(); // 没有强制转换到Person类型 in.close(); System.out.println(newPerson); } }
知识点提炼
- File类用于获得文件属性和操作文件。
- InputStream类和OutputStream类是所有二进制I/O类的根类。FileInputStream和FileOutputStream类关联一个文件用于输入/输出。BufferedInputStream和BufferedOutputStream类可以包装任何一个二进制输入/输出流提高性能。
- Reader类和Writer类是所有字符I/O类的根类。FileReader和FileWriter类关联一个文本文件用于输入/输出。BufferedReader和BufferedWriter类可以包装任何一个字符输入/输出流提高性能。
习题
- 编写一程序,允许用户通过对话框将选中文件的文件复制到指定位置。
- 编写简单的记事本程序,允许用户编辑、查看、保存文本文件。
返回 Java程序设计