How to create a backup file if the file exists

Jixo :

I would like to create a backup backup_autoexec" + value + ".cfg of my file autoexec.cfg if it exists. If there is also already and backup then it should increase the value number. for example backup1, backup2, backup3...

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 it will hang into the while loop for ever and I dont know why.

Nikolas :

You check the existence only once - for the first file. Here is a minimal working example:

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;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=157023&siteId=1