在Java程序执行过程中,很多数据都是以对象的方式存在于内存当中。有时会希望直接将内存中的整个对象存储至文件,而不是只存储对象中的某些特定成员信息。ObjectInputStream和ObjectOutputStream这2个包装类就用于从底层输入流中读取对象类型的数据和将对象类型的数据写入到底层输出流。
需要注意的是ObjectInputStream和ObjectOutputStream类所读写的对象必须实现了java.io.Serializable接口。对象中的transien和static类型的成员变量不会被读取和写入。不过Serializable接口中并没有规范任何必须实现的方法,所以这里所谓实现的意义,其实就像是对对象贴上一个标志,代表该对象是可序列化的。
下面我们来写个实例来演示一下:
创建一个可序列化的学生对象,并用ObjectOutputStream把它存储到一个students.txt的文本文件中,然后用ObjectInputStream类把存储的数据读取到一个学生对象中。
首先定义一个学生类,有4个属性,实现Serializable接口
Students.java
package com.richer.io; import java.io.Serializable; public class Students implements Serializable { int id; String name; int age; String department; //系别 public Students(int id, String name, int age, String department) { super(); this.id = id; this.name = name; this.age = age; this.department = department; } }
然后定义一个执行类。
ObjectStreamTest.java
package com.richer.io; import java.io.*; public class ObjectStreamTest { public static void main(String[] args) throws Exception { //在文件中写入信息 Students stu1= new Students(1, "Richer", 24, "系1"); Students stu2= new Students(2, "IsFung", 24, "系2"); FileOutputStream fos =new FileOutputStream("students.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(stu1); oos.writeObject(stu2); oos.close(); //读取信息 FileInputStream fis =new FileInputStream("students.txt"); ObjectInputStream ois = new ObjectInputStream(fis); stu1 = (Students) ois.readObject(); stu2 = (Students) ois.readObject(); System.out.println("ID:" + stu1.id + " 姓名:" + stu1.name + " 年龄:" + stu1.age + " 系别:" + stu1.department); System.out.println("ID:" + stu2.id + " 姓名:" + stu2.name + " 年龄:" + stu2.age + " 系别:" + stu2.department); ois.close(); } }
版权声明: 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。