0
將對象保存到文件時出現了一些問題。我有FileManager類,其中包含將對象保存到文件的方法。此方法用於包含主循環的類Control(選擇不同的選項)。我想選擇選項EXIt保存對象,但沒有任何反應。當我添加新的選項(即6 - 保存數據庫)程序正常工作。我會感謝任何可能出錯的線索。序列化,保存對象
class FileManager {
package utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import data.DataBase;
public class FileManager {
public static final String FILE_NAME = "file.txt";
public void writeDataBaseToFile(DataBase db) {
try (
FileOutputStream fos = new FileOutputStream(FILE_NAME);
ObjectOutputStream oos = new ObjectOutputStream(fos);
) {
oos.writeObject(db);
} catch (FileNotFoundException e) {
System.err.println("Błąd");
} catch (IOException e) {
System.err.println("Błąd");
}
}
}
控制類:
class Control {
package app;
import data.DataBase;
import data.Expense;
import data.Income;
import utils.AccountInfo;
import utils.AddData;
import utils.FileManager;
import utils.Info;
import utils.Options;
public class Control {
private AccountInfo account;
private AddData addData;
private DataBase dataBase;
private Info inf;
private Income income;
private FileManager fileManager;
public Control() {
addData = new AddData();
dataBase = new DataBase();
inf = new Info(dataBase);
account = new AccountInfo(dataBase);
fileManager = new FileManager();
}
public void ControlLoop() {
Options option;
printOptions();
while((option = Options.createOption(addData.getOption())) != Options.EXIT) {
try {
switch(option) {
case ADD_INCOME:
addIncome();
break;
case ADD_EXPENSE:
addExpense();
break;
case PRINT_INCOME:
printIncome();
break;
case PRINT_EXPENSE:
printExpense();
break;
case RESUME_ACCOUNT:
resumeAccount();
break;
case EXIT:
saveData();
}
} catch(NullPointerException ex) {
}
printOptions();
}
addData.close();
}
public void addIncome() {
income = addData.createIncome();
dataBase.addBudget(income);
}
public void addExpense() {
Expense expense = addData.createExpense();
dataBase.addBudget(expense);
}
public void printIncome() {
inf.printIncome();
}
public void printExpense() {
inf.printExpense();
}
public void resumeAccount() {
account.resumeIncome();
account.resumeExpense();
}
public void saveData() {
fileManager.writeDataBaseToFile(dataBase);
}
public void printOptions() {
System.out.println("Wybierz opcję:");
for(int i=0; i<6; i++) {
System.out.println(Options.values()[i]);
}
}
}
嘗試添加一箇中斷; EXIT案例後 – maxTrialfire
歡迎使用堆棧溢出!它看起來像你需要學習使用調試器。請幫助一些[互補調試技術](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。如果您之後仍然有問題,請隨時返回更多詳情。 –