package com20101128;import java.io.*;
import java.util.ArrayList;
import java.util.Collection;class Student implements Serializable { private String name;
private int num; public Student(String name, int num) {
this.name = name;
this.num = num;
} @Override
public String toString() {
return "姓名:" + name + "年龄:" + num;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getNum() {
return num;
} public void setNum(int num) {
this.num = num;
}}public class TestSerializable { public static void save(File f, Collection<Student> s) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(f));
for (int i = 0; i < s.size(); i++) {
oos.writeObject(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} public static void readOut(File f, Collection<Student> students) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(f));
Student s = null;
for (int i = 0; i < students.size(); i++) {
s = (Student) ois.readObject();//就是这里出问题!!!!
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} public static void main(String[] args) {
File f = new File("G:\\baocun.txt");

Student s1 = new Student("王印彬", 21);
Student s2 = new Student("王旭兴", 22);
Student s3 = new Student("胡蓉", 20);

Collection<Student> students = new ArrayList<Student>() ;
students.add(s1);
students.add(s2);
students.add(s3);

System.out.println(students);

/*Student[] student = new Student[2];
student[0] = new Student("王印彬", 21);
student[1] = new Student("王旭兴", 22);*/ save(f, students);
//readOut(f, students);
}}不懂为什么总是不能转换类型?很急呀····

解决方案 »

  1.   

    调用这个方法除问题了··readOut(f, students);
      

  2.   

    Object对象流不能这么读的如果你保存的是一个 Student 对象没问题,但是你要保存一个集合,那么 readObject 读出来的是一个集合(Collection)ois.readObject然后你再去遍历这个集合,对里面的元素强转为 Student对象类型序列化是整个对象,文件系统是不会知道你存储的是一个接一个的 Student对象希望能帮助你
      

  3.   

    更正下(ArrayList)ois.readObject....
      

  4.   

    能不能给个具体实现的代码··貌似不是这个原因,他会一个一个的读的
    我readOut(f, students);传的集合只是要用他的长度··读几个对象而已,他会一个一个读取的
      

  5.   


    try {
    ois = new ObjectInputStream(new FileInputStream(f));
    ArrayList<Student> tempList = (ArrayList<Student>) ois.readObject();
    for (int i = 0; i < tempList.size(); i++) {
    Student s = tempList.get(i);
    System.out.println(s);
    }
    }