【发布时间】:2017-01-13 08:34:58
【问题描述】:
对于我的应用程序,我想使用 Map 作为数据库。为了保存和加载地图,我使用以下两种方法将其写入/读取到 database.ser:
private synchronized void saveDB() {
try {
fileOut = new FileOutputStream(db);
out = new ObjectOutputStream(fileOut);
out.writeObject(accounts);
fileOut.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void loadDB() {
try {
fileIn = new FileInputStream(db);
in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
accounts = (Map<String, Client>) in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我想在应用程序启动时加载到 Map,所以我在构造函数中调用方法如下:
protected DriveatorImpl() {
accounts = new ConcurrentHashMap<String, Client>();
db = new File("C:/Users/eduar/git/Multy-Threaded-Bank-System/Bank-Services/database.ser");
// also, any suggestions how can I make path to a file more flexible in case I want to run Server side of an app on different machine?
if (!db.exists()) {
try {
db.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
loadDB(); // loads database when server start
}
我知道是什么导致了错误,但我不知道我应该在设计中进行哪些更改以避免 ObjectInputStream 构造函数接收空流! 关于我可以做些什么不同的任何建议?
编辑:我想指出,在新的应用程序运行中 database.ser 是空的,因为还没有进入 Map 的条目。
谢谢!
【问题讨论】:
标签: java oop objectinputstream eofexception