★☆

★☆
posts - 0, comments - 0, trackbacks - 0, articles - 80
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

将对象写入文件,在以对象读出

Posted on 2008-08-13 12:57 阅读(219) 评论(0)  编辑  收藏 所属分类: J2SM
将对象写入文件,在以读出对象:

//两个student对象
Student stu1=new Student(19,"zhangsan",25,"Chemist");
Student stu2=new Student(20,"lis",30,"Physics");

//将stu1和stu2写入student.txt文件中  
FileOutputStream fos=new FileOutputStream("student.txt");
ObjectOutputStream os=new ObjectOutputStream(fos);
os.writeObject(stu1);
os.writeObject(stu2);
os.close();

//从student.txt文件中读出stu3和stu4
Student stu3 = null;
Student stu4 = null;
FileInputStream fis=new FileInputStream("student.txt");
ObjectInputStream is=new ObjectInputStream(fis);
stu3=(Student)is.readObject();
stu4=(Student)is.readObject();
is.close();