eam("a.txt"));
/* //读取对象
java.lang.Object obj = ois.readObject();
System.out.println(obj);
java.lang.Object obj2 = ois.readObject();
System.out.println(obj2);
java.lang.Object obj3 = ois.readObject();
System.out.println(obj3);*/
try{
while(true)
{
java.lang.Object obj = ois.readObject();
System.out.println(obj);
}
} catch(EOFException e){
System.out.println("读到了文件的末尾");
}
//释放资源
ois.close();
}
// 另一种方式写入
private static void method3() throws IOException, FileNotFoundException {
// 另一种写入对象文件的方式(将所有对象写入到集合对象中)
//创建对象输出流对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("b.txt"));
//创建集合对象
ArrayList<Student> list = new ArrayList<Student>();
//添加学生对象
list.add(new Student("wangwu", 19));
list.add(new Student("zhaoliu", 20));
//写出集合对象
oos.writeObject(list);
//释放资源
oos.close();
}
//另一种读取方式
private static void method4() throws IOException, FileNotFoundException, ClassNotFoundException {
//创建对象输出流对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("b.txt"));
//读取数据
java.lang.Object obj = ois.readObject();
//System.out.println(obj);
// 向下转型,获取具体的子类对象
ArrayList<Student> list = (ArrayList<Student>) obj;
for(Student stu:list)
{
System.out.println(stu);
}
//释放资源
ois.close();
}
|