Java - 如果文本文件存在,则创建新文件追加" 1"

时间:2015-01-06 21:07:40

标签: java count append

如何更改代码以查找现有的" 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();

            }

1 个答案:

答案 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