各位,我想问一下为什么我的ObjectInputStream里read()会等于-1啊!!import java.io.*;
import java.util.*;public class TestStream
{
public static void main(String args[]) throws Exception//main function to create the ObjectStream
{
Student[] students = {new Student("liuzesen","3110005806"),
                    new Student("liuzebiao","3110005807"),
                    new Student("liuzebin","3110005808")};
String str = "Object.txt";
writeObjectToFile(students,str);
/*
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Object.txt"));
Student ss = (Student)ois.readObject();
System.out.printf("%s%s",ss.getName(),ss.getNum());
    ois.close();
    */
    Student[] sss = readObjectFile(str);
    for(Student st: sss)
    {
     System.out.printf("%s%s",st.getNum(),st.getName());
    }
}

public static void writeObjectToFile(Object[] object,String filename)//a function to add Object
{
try
{
int index = 1;
ObjectOutputStream oot = new ObjectOutputStream(new FileOutputStream(new File(filename)));
for(Object obj: object)
{
System.out.println("" + index + " number is added");//CHECK!!!!!!!!
oot.writeObject(obj);
index++;
}
oot.flush();
oot.close();
}catch(IOException e){
e.printStackTrace();
} }

public static Student[] readObjectFile(String filename)//read the Ojbect Stream
{
List<Student> studentList = new ArrayList<Student>();
System.out.println("aa");//CHECK!!!!
try
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(filename)));
int check = -1;
int index = 1;
System.out.println("" + ois.read());//CHECK!!!!!
try{
while((check = ois.read()) != -1)
{
System.out.println("" + index + " number is read");//CHECK!!!!!!!
studentList.add((Student)ois.readObject());
index++;
}
}catch(ClassNotFoundException e)
{e.printStackTrace();}
ois.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}

Student[] stu = new Student[studentList.size()];
return studentList.toArray(stu);
}
}class Student implements Serializable//the Object which is obtained in the Stream
{
private static final long serialVersionUID = 1L;//id
public Student()
{

}
public Student(String name,String num)
{
this.name = name;
this.num = num;
}
public String getName()
{
return name;
}
public String getNum()
{
return num;
}

private String name = null;
private String num = null;
}

解决方案 »

  1.   

    存入的时候是按Object对象存入的取的时候也应该按Object对象来取吧
    try{
    Student s = (Student)ois.readObject();
    System.out.println("" + s.getName());//CHECK!!!!!
    }catch(Exception e){
    e.printStackTrace();
    }
    ois.skip(18);
    //因为第一个对象站了 18个字节,这样就可去出来第二个对象了
    try{
    Student s = (Student)ois.readObject();
    System.out.println("" + s.getName());//CHECK!!!!!
    }catch(Exception e){
    e.printStackTrace();
    }
      

  2.   

    刚才我自己又试了一下,如果把readObjectFile(String filename)的static去掉,然后用new TestStream().readObjectFile(str) 就可以了。。这又是何解