目前正在撰寫一個像Booking這樣的應用程式,我正處于將我的資訊存盤在檔案中的階段。我創建了一個Serializable Database類,它有一個帶有路徑名的欄位和 2 個讀/寫方法。我有大約 8 個其他類可以擴展資料庫,每個類都包含一個Hashmap和一些查詢方法。當然Databases,我在啟動應用程式之前從我的檔案中讀取了,并在退出之前寫入,但是我遇到了一個問題,我正在讀取的物件都是null。我已經研究了 2 個小時,我需要第二個意見。這是資料庫的讀/寫方法:
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課堂上加載它們的方式(這可能是問題所在)
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();
}
可能會詢問的一些額外資訊:
- 我存盤的所有類都是可序列化的
- 我存盤資料庫的檔案都是 *.ser (這是我找到的擴展名)
- 檔案存盤在專案中
uj5u.com熱心網友回復:
如果您的read()方法在沒有 EOFException 的情況下完成,則它以return null;. 你應該return obj;,你閱讀的物件。
如果您的讀取成功,您不應期望會拋出 EOFException。EOFException 表示它在嘗試讀取您的物件時用完了資料,并且無法成功完成。
如果您確實收到 EOFException,那么給出一些指示而不是靜默回傳可能是個好主意。靜默的 catch 塊拒絕了對除錯有用的資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360982.html
