从 Java 中的文件加载错误



>我必须为 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 条记录。这个想法是我将它们全部加载到数组列表中,以备将来在程序中使用。我也没有拿回任何渔获物。有什么帮助吗?谢谢:)

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

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);
        }

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

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

然后你可以从数组列表中一个接一个地获取你的对象

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

  //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();

相关内容

  • 没有找到相关文章

最新更新