灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:1698回复:0

实例分析:例3:保存所有的Person对象到文件并以对象的方式读出来

楼主#
更多 发布于:2012-09-08 09:36


1 问题分析
本题中需要对文件读,写对象数据,需要使用到与对象有关的流ObjectInputStream/ObjectOutputStream。
2 使用对象的读写流
ObjectOutputStream用于将一个对象输出,输出对象使用的方法为writeObject(Object obj)
ObjectInputStream用于读取一个对象,读取对象使用的方法为readObject()
注意: 被读写的对象必须是已序列化的类的对象,即要实现要Serializable接口。
3 编写代码
[java]
import java.io.*;
import java.util.*;

class Person implements Serializable {
    String name = null;

    public Person(String s) {
        name = s;
    }

    public String toString() {
        return name;
    }
}

public class TestObjectStream {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            File f = new File("date.ser");
            oos = new ObjectOutputStream(new FileOutputStream(f));
            oos.writeObject(new Person("andy"));
            oos.close();

            ois = new ObjectInputStream(new FileInputStream(f));
            Person d = (Person) ois.readObject();
            System.out.println(d);
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
import java.io.*;
import java.util.*;
class Person implements Serializable {
String name = null;
public Person(String s) {
  name = s;
}
public String toString() {
  return name;
}
}
public class TestObjectStream {
public static void main(String[] args) {
  ObjectOutputStream oos = null;
  ObjectInputStream ois = null;
  try {
   File f = new File("date.ser");
   oos = new ObjectOutputStream(new FileOutputStream(f));
   oos.writeObject(new Person("andy"));
   oos.close();
   ois = new ObjectInputStream(new FileInputStream(f));
   Person d = (Person) ois.readObject();
   System.out.println(d);
   ois.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
}
}
4 编译运行
javac TestObjectStream.java
java TestObjectStream


喜欢0 评分0
游客

返回顶部