【发布时间】:2015-01-08 20:19:40
【问题描述】:
我正在开发一个以这种格式存储技术手册的小型图书馆应用程序:
目前,我正在尝试让用户按需将库的内容保存和加载到 bin 文件中。
但是,当我尝试加载库文件时,唯一的变化是“-1”被打印到控制台。此处显示:
理想情况下,我希望将加载的手册存储到用户当前的库中。
这是我的代码:
//Choice 7: Load Library:
if(Menu.menuChoice == 7){
boolean loadYesNo = Console.readYesNo("\n\nThe manualKeeper app is able to load and display any 'Library.txt' files \nfound in your home folder directory.\n\nWould you like to load and display library? (Y/N):\n");
String fileName = "Library.bin";
if(loadYesNo==true){
try {
FileInputStream fileIs = new FileInputStream(fileName);
ObjectInputStream is = new ObjectInputStream(fileIs);
Object x = is.read();
System.out.println(x);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Menu.displayMenu();
}
else if(loadYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not loaded!\n");
System.out.println("--------------------------------------------------------------------------\n");
Menu.displayMenu();
}
}
//Choice 0: Exit the program:
if(Menu.menuChoice == 0){
if(Menu.menuChoice == 0){
if(Library.ManualList.size() > 0){
boolean saveYesNo = Console.readYesNo("\nThe manualKeeper app is able to save your current library to a '.txt' \nfile in your home folder directory (C:\\Users\\ 'YOUR NAME').\n\nWould you like to save the current library? (Y/N):\n");
String fileName = "Library.bin";
if(saveYesNo==true){
try {
FileOutputStream fileOs = new FileOutputStream(fileName);
ObjectOutputStream os = new ObjectOutputStream(fileOs);
for (int i = 0; i < Library.ManualList.size(); i++){
os.writeObject(Library.ManualList.get(i).displayManual());
os.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DONE WRITING!");
}
else if(saveYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not saved!\n");
System.out.println("--------------------------------------------------------------------------\n");
break exit;
}
Menu.displayMenu();
}else if(Library.ManualList.isEmpty()){
Menu.displayMenu();
}
}
}
}
System.out.println("\n ~ You have exited the manualKeeper app! ~ ");
System.out.println("\n Developed by Oscar Moore - 2014 - UWL\n");
System.out.println("\n <3\n");
}
}
如果需要显示更多代码,请告诉我。谢谢。
【问题讨论】:
-
您将文本/字符串数据保存到 .bin(二进制)文件有什么特别的原因吗?例如,而不是简单的 .txt?
-
@colti 我真的想要一种简单的方法来保存我的库并从保存文件中导入它,我已经为此苦苦挣扎了一段时间
-
我建议更改文件扩展名作为一种好习惯 - 当它不是二进制数据时将其保存为 .bin 有点令人困惑(或将非 mp3 数据保存到 .mp3 文件等) .