如何更改代码以查找现有的" Library.txt"文件,如果存在,创建一个名为" Library1"等的新文件?
我目前有这个代码:
if(Menu.menuChoice == 7 && Library.ManualList.isEmpty()){
System.out.println(Messages.addManualFirst);
Menu.displayMenu();
}
else if(Menu.menuChoice == 7){
Library.displayManualList();
boolean saveYesNo = Console.readYesNo("\nThe manualKeeper® app is able to save your current library to a '.txt' \nfile in your workspace directory.\n\nWould you like to save the current library? (Y/N):\n");
if(saveYesNo){
try {
File file = new File("Library.txt");
file.delete();
file.createNewFile();
FileWriter fw = new FileWriter(file, true);
PrintWriter pw = new PrintWriter(fw);
for (int i = 0; i < Library.ManualList.size(); i++){
pw.println("\n-------------------- Index Number: " + i + " --------------------");
pw.println(Library.ManualList.get(i).displayManual());
pw.println("---------------------------------------------------------");
}
pw.close();
} catch (IOException e) {
System.out.println("Error! Library unable to save.");
}
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library saved!\n");
System.out.println("--------------------------------------------------------------------------\n");
}
else if(saveYesNo){
System.out.println("\n");
}
Menu.displayMenu();
}
答案 0 :(得分:1)
请勿拨打file.delete()
,这将删除现有的!我想你想要像
File file = new File("Library.txt");
// file.delete();
// file.createNewFile();
for (int i = 1; file.exists(); i++) {
file = new File(String.format("Library%d.txt", i));
}
您可以将其视为声明并将i
初始化为1
,而file
存在则向i
添加一个。将file
(暂时)重新初始化为{#1}}&#34;图书馆#.txt&#34;其中String
被#
取代。
您可以阅读格式化程序语法here。