如果文件存在,如何创建备份文件

时间:2019-05-16 16:59:31

标签: java file while-loop

如果文件backup_autoexec" + value + ".cfg存在,我想为其创建备份autoexec.cfg。如果还已经有备份,则应增加值编号。例如backup1backup2backup3 ...

public class Backup {

    private int value1 = 0;
    private String value;
    private File file = new File("autoexec.cfg");
    private boolean exists = file.exists();
    private Path backup;
    private Path auto = Paths.get("autoexec.cfg");

    public void kopie() {

        if(exists) {        
            while(exists) {
                System.out.println("test");
                value1 += 1;
                value = String.valueOf(value1);
                file = new File("backup_autoexec" + value +                   ".cfg");
                backup = Paths.get("backup_autoexec" + value + ".cfg");

            }

                try {
                    Files.move(auto, backup);
                }
                catch (IOException f) {
                    f.printStackTrace();
                }   
        }
    }
}

atm永远挂在while循环中,我不知道为什么。

2 个答案:

答案 0 :(得分:1)

对于第一个文件,您只能检查一次。这是一个最小的工作示例:

int index = 1;
while (true) {
    final String source = "autoexec" + index + ".txt";
    if (new File(source).exists()) {            
        Files.copy(Paths.get(source), Paths.get(path + "\\backup_file" + index + ".txt")); 
        index++;
    } else {
        break;
    }
}

答案 1 :(得分:0)

如果找不到使用现有名称的文件,则应该退出循环