-1

我必须为 java 项目实现对象文件,但是在加载文件时遇到问题(保存一切正常)

public static void loadStudentList() {
    boolean endOfFile = false;

    try {
        // create a FileInputStream object, studentFile
        FileInputStream studentFile = new FileInputStream("Students.obf");
        // create am ObjectImnputStream object to wrap around studentStream
        ObjectInputStream studentStream = new ObjectInputStream(studentFile) ;

        // read the first (whole) object with the readObject method
        Student tempStudent = (Student) studentStream.readObject();
        while (endOfFile != true) {
            try {
                tempStudent = (Student) studentStream.readObject();
                stud1.add(tempStudent);
            }
            catch(EOFException e) {
                endOfFile = true;
            }
        }
        studentStream.close();
        //use the fact that the readObject throws an EOFException to check whether the end of eth file has been reached
    }
    catch(FileNotFoundException e) {
        System.out.println("File not found");
    }

    catch(ClassNotFoundException e) {  // thrown by readObject
    /* which indicates that the object just read does not correspond to any class
known to the program */
        System.out.println("Trying to read an object of an unkonown class");
    }
    catch(StreamCorruptedException e) { //thrown by constructor
    // which indicates that the input stream given to it was not produced by an ObjectOutputStream object
        System.out.println("Unreadable File Format");
    }
    catch(IOException e) {
        System.out.println("There was a problem reading the file");
    }
}

这是我用来加载文件的代码。该程序将加载我文件中的最后 2 条记录。想法是我将它们全部加载到一个数组列表中,以备将来在程序中使用。我也没有得到任何我的收获。有什么帮助吗?谢谢 :)

4

2 回答 2

0

为什么不将对象添加到ArrayList<Type>然后将它们写入/序列化到文件中,然后为了读取/反序列化它,将数据读入一个ArrayList<Type>.

然后你可以从 ArrayList 中一一获取你的对象

这可能是一种更简单的无故障方式。

  //Serialize
  ArrayList<Student> students = new ArrayList<Student>();
  //Add the student objects to the array list
  File f = new File("FileName.ser");
  ObjectOutputStream objOut = new ObjectOutputStream(new FileOutputStream(f));
  objOut.writeObject(students);

   //Deserialize
   ArrayList<Student> students = new ArrayList<Student>();
   ObjectInputStream objIn = new ObjectInputStream(new FileInputStream(new File("FileName.ser")));
   students = (ArrayList<String>) objIn.readObject();
于 2013-01-24T07:56:23.367 回答
0

您永远不会将您阅读的第一个学生添加到列表中

Student tempStudent = (Student) studentStream.readObject();
         while (endOfFile != true)
        {
            try
            {

                 tempStudent = (Student) studentStream.readObject();
                 stud1.add(tempStudent);
            }

删除while之前的读取,如下面的代码

     while (endOfFile != true)
    {
        try
        {

             Student tempStudent = (Student) studentStream.readObject();
             stud1.add(tempStudent);
        }

我不确定这是否能解决您的问题

于 2013-01-24T08:00:33.027 回答