[英]Java - Reading & writing array to/from BIN file
我正在使用一个小型图书馆应用程序,该应用程序以这种格式存储技术手册:
当前,我正在尝试使该库的内容能够保存并根据用户的需要加载到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");
}
}
如果需要显示更多代码,请告诉我。 谢谢。
这些行:
Object x = is.read(); System.out.println(x);
导致您在控制台中看到的-1。
从javadocs( link ), read()
返回:
如果到达流的末尾,则为-1。
因此,首先,检查Library.bin
是否正确保存(保存后使用文本编辑器)。
然后,确保要读取的文件是相同的文件。
看来您没有使用文件的完整路径。 例如Library.bin
与/home/project/Library.bin
。 尝试使用完整路径。 我怀疑这是问题所在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.