Frage

java.io.File s1 = new java.io.File("/saves/save1.sav");
java.io.File s2 = new java.io.File("/saves/save2.sav");
java.io.File s3 = new java.io.File("/saves/save3.sav");
java.io.File s4 = new java.io.File("/saves/save4.sav");

This code sets the s variables to the location of specific files. I am looking for a way to use a for loop to check if variable s+"i" exists until it finds that it doesn't exist, then creates a new file named "save+"i".sav". (The +"i" means the number that will go after it.) Basically, I want it to create a new save file that does not overwrite other save files if there are any and gives it the name of "save(save #).sav". The code above may become obsolete. This way, I won't have to write a bunch of if statements and I can put all the code in a single statement. Thanks in advance to anyone willing to help. -Santiago

War es hilfreich?

Lösung

There are two parts to your question you can figure out separately, then just put them together.

First, you want to have a loop that looks at different filenames which only differ by an integer. You can do this by incrementing the integer in a for loop and using String.format() to make your path:

for (int n = 1; n <= 4; n++) {
    String filePath = String.format("/saves/save%d.sav", n);
    // ....
}

Once you have each filePath in this loop (set the range of integers how you like), you just need to check if it exists (which is explained here) and if not, create it:

for (int n = 1; n <= 4; n++) {
    String filePath = String.format("/saves/save%d.sav", n);
    File checkFile = new File(filePath);
    if (!checkFile.exists()) {
       try {
           checkFile.createNewFile();
           // If you want to write content to the file, do it here...
       } catch (IOException e) {
           e.printStackTrace();
       }
    } 
}

Andere Tipps

File path_file = new File("/saves");
File f = null;
int i = 0;
while (f == null || f.exists()) {
    i++;
    String filename = "save" + i + ".sav";
    f = new File(path_file, filename);
}

Then f would be your new file.

Disclaimer: I haven't programmed in Java for a while.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top