在此方法中创建新的.ser文件有什么问题?

时间:2018-02-19 01:09:33

标签: java object serialization

我正在尝试创建一个新的.ser文件来存储对象(如果没有已存在的对象)。运行此命令时,它会抛出EOFException。究竟什么是EOFException并且正确编写此方法来创建和读取.ser文件?感谢您的任何反馈。

public void addCourseForStudents() {
    Long CIN;
    System.out.println("please enter your CIN : ");
    CIN = in.nextLong();
    for (Student s : studList) {
        if (s.getStudentCIN().equals(CIN)) {
            outerloop(s);
                }
            }
}
public void outerloop(Student s) {
String courseId;
int numberOfUnits;
int position = 0;
System.out.println(" Enter the course details : ");
System.out.println();
System.out.println(" Enter the course Id : ");
courseId = in.next();
System.out.println(" Enter the number of units : ");
numberOfUnits = in.nextInt();
for (Course c : courseList) {
    if (c.getCourseId().equals(courseId) && numberOfUnits == 
c.getNumberOfUnits()) {
        s.getCourseSchedule().add(c);
    }
    else position++;}
} 

EOFException类:

public void readDatabase() throws IOException {

        File dataFile = new File("database.ser");

        // If data file does not exist, create it.
        if (!dataFile.exists()) {
            System.out.println("database.ser does not exist, creating one now . . .");
            // if the file doesn't exists, create it        
            dataFile.createNewFile();
            return; // No need to try to read anything from an empty file, so return.
        }
        ObjectInputStream objectinputstream = null;
        boolean cont = true;
        try {
            FileInputStream streamIn = new FileInputStream(dataFile);
            objectinputstream = new ObjectInputStream(streamIn);
            while (cont) {
                Item obj = null;
                try {
                    obj = (Item) objectinputstream.readObject();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                if (obj != null)
                    itemList.add(obj);
                else
                    cont = false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectinputstream != null) {
                objectinputstream.close();
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

EOFException代表:

  

文件结束例外

当您尝试从FileReader到达文件末尾的文件中读取数据时,通常会发生这种情况。换句话说,没有更多的数据可供阅读。

您应该捕获异常并关闭您的流。因为它表示您已经读取了文件中的所有对象。参考answer in this question

 while (true) {
        try {
            // Read the next object from the stream. If there is none, the
            // EOFException will be thrown.

            Item obj = (Item) objectinputstream.readObject();
            itemList.add(obj);
        } catch (EOFException e) {
            // If there are no more objects to read, return what we have.
            return contactMap;
        } finally {
            // Close the stream.
            in.close();
        }
    }