反序列化 returns 空对象 Java

Deserializing returns null object Java

目前正在编写类似 Booking 的应用程序,我正处于将信息存储在文件中的阶段。我创建了一个 Serializable Database class ,它有一个带有路径名的字段和 read/write 的2个方法。我还有大约 8 个其他 classes 扩展数据库,每个都有一个 Hashmap 和一些查询方法。自然地,我在启动应用程序之前从我的文件中读取 Databases 并在退出之前写入,但是我 运行 遇到了一个问题,我正在读取的对象都是 null.我已经研究了 2 个小时了,我需要第二个意见。这是数据库的 read/write 方法:

public void write() {
        try {
            File temp = new File(this.filename);
            temp.createNewFile(); // create file if not present
            FileOutputStream fileOut = new FileOutputStream(this.filename);
            ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
            objectOut.writeObject(this);
            objectOut.close();
            System.out.println("The Object  was successfully written to a file");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public Object read() {
        Object obj = null;
        try {
            File temp = new File(this.filename);
            temp.createNewFile(); // create file if not present
            FileInputStream fileIn = new FileInputStream(this.filename);
            ObjectInputStream objectIn = new ObjectInputStream(fileIn);
            obj = objectIn.readObject();
            System.out.println("The Object was successfully read from the file");
            objectIn.close();
        } catch (EOFException ex) {
            return obj;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

这是我在 Application class

中加载它们的方式(这可能是问题所在)
private void loadData() {
        accommodationReviewsDatabase = (AccommodationReviews) accommodationReviewsDatabase.read();
        brokerAccommodationsDatabase = (BrokerAccommodations) brokerAccommodationsDatabase.read();
        credentialsUserDatabase = (CredentialsUser) credentialsUserDatabase.read();
        customerReviewsDatabase = (CustomerReviews) customerReviewsDatabase.read();
        userConfirmationsDatabase = (UserConfirmations) userConfirmationsDatabase.read();
        userMessagesDatabase = (UserMessages) userMessagesDatabase.read();
    }

    private void writeData() {
        accommodationReviewsDatabase.write();
        brokerAccommodationsDatabase.write();
        credentialsUserDatabase.write();
        customerReviewsDatabase.write();
        userConfirmationsDatabase.write();
        userMessagesDatabase.write();
    }

可能会询问的一些额外信息:

如果您的 read() 方法在没有 EOFException 的情况下完成,它将以 return null; 结束。你应该return obj;,你读的对象

如果读取成功,您不应期望抛出 EOFException。 EOFException 表示它在尝试读取您的对象时 运行 数据不足,无法成功完成。

如果您 遇到 EOFException,给出一些指示而不是默默地返回可能是个好主意。静默捕获块拒绝提供可能对调试有用的信息。