0

I am using the .exists() method to make sure a file does not exists and if it does, it adds a number to the file. However, it is not working and creating the file using the original filename and essentially overwriting the previous when creating another one.

This is my code:

int count = 1;
String name = "myFileName" + count;
String path = "/pathway/";
String ext = ".txt";

File file = new File(path + name + ext);
if (file.exists()) {
    System.out.println("file found!");
    name = "myFileName" + (count++);
    file = new File(path + name + ext);
}

System.out.println("wrote file: " + name); 

The output is this whenever I run it over again:

[1:47:40:359] wrote file: myFileName1

[1:47:40:361] wrote file: myFileName1

Tae
  • 19
  • 3
  • `count++` is post update (will be update AFTER), you might want `++count` which is a pre update – MadProgrammer May 03 '21 at 06:01
  • And for a few more ideas on the same concept, see [this example](https://stackoverflow.com/questions/18324203/screenshot-saving-as-autogenerated-file-name/18324758#18324758) – MadProgrammer May 03 '21 at 06:03
  • You can use **name = "myFileName" + (count+1);** – sanjeevRm May 03 '21 at 06:04
  • 1
    @sanjeevRm, that will work only once. If OP does not continue counting, if myFileName2 or myFileName3 exist, they will overwrite the next file respectively. – TreffnonX May 03 '21 at 06:05

1 Answers1

1

Your mistake is the count++. The postfixed ++ operator first 'returns' the value and then increments it. You need to first increment, and then return. Do this with the prefixed ++ operator: ++count

A while loop should help, to ensure, that you create a new file, even if the previous existed, even if a second or third also exists.

int count = 1;
String name = "myFileName" + count;
String path = "/pathway/";
String ext = ".txt";
File file = new File(path + name + ext);

while (file.exists()) {
    System.out.println("file found!");
    name = "myFileName" + (++count);
    file = new File(path + name + ext);
}

System.out.println("wrote file: " + name); 
TreffnonX
  • 2,924
  • 15
  • 23