对象序列化流:
代码如下:
package ObjectOutputStreamPack;import java.io.Serializable;public class Student implements Serializable {private String name;private int age;public Student() {}public Student(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}
package ObjectOutputStreamPack;import java.io.*;public class ObjectOutputStreamDemo
{public static void main(String[] args) throws IOException {ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\JavaDemo\\oos.txt"));Student s = new Student("Tom",33);oos.writeObject(s);oos.close();}}
对象反序列化流:
代码如下:
package ObjectOutputStreamPack;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;public class ObjectInputStreamDemo {public static void main(String[] args) throws IOException, ClassNotFoundException {ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\JavaDemo\\oos.txt"));Object obj = ois.readObject();Student s = (Student) obj;System.out.println(s.getName()+","+s.getAge());ois.close();}}