ObjectOutputStream和ObjectInputStream类的学习
ObjectOutputStream和ObjectInputStream类所读写的对象必须实现了Serializable的接口,对象中的transient和static类型的成员变量不会被读取和写入.下面写个简单的例子:
1. SerializationTest.java文件
package cn.com;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;public class SerializationTest {public static void main(String[] args) {Student student1 = new Student(19, "zhangsan", 25, "chemistry");Student student2 = new Student(20, "lisi", 23, "phsical");try {FileOutputStream fos = new FileOutputStream("student.txt");ObjectOutputStream os = new ObjectOutputStream(fos);os.writeObject(student1);os.writeObject(student2);os.close();FileInputStream fis = new FileInputStream("student.txt");ObjectInputStream is = new ObjectInputStream(fis);try {student1 = (Student) is.readObject();student2 = (Student) is.readObject();is.close();System.out.println("id1 = " + student1.id);System.out.println("name1 = " + student1.name);System.out.println("id2 = " + student2.id);System.out.println("name2 = " + student2.name);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
2.Student.java文件
package cn.com;import java.io.Serializable;public class Student implements Serializable {int id;String name;int age;String department;public Student(int id, String name, int age, String department) {this.id = id;this.name = name;this.age = age;this.department = department;}}
页:
[1]