- import java.io.*;
- class ObjectStreamDemo {
- public static void main(String[] args) throws IOException {
- writeObj();
- }
- public static void readObj() throws IOException, Exception {
- ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
- "obj.txt"));
- Person p = (Person) ois.readObject();
- System.out.println(p);
- ois.close();
- }
- public static void writeObj() throws IOException {
- ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
- "obj.txt"));
- oos.writeObject(new Person("lisi", 39));
- oos.close();
- }
- }
- class Person implements Serializable{
- String name;
- int age;
- Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- public String toString() {
- return name + ":" + age;
- }
- }
复制代码 楼主程序中Person类要实现序列化接口,才能进行二进制数据流传输。 |