duration duration - 29 days ago 5
Java Question

Create multiple copies of a singlle file in java

i have a fileserver and client and want to rename files, if they already exists in downloadfolder. what is the best way to do that? I tried that code but it always create one copy and the next copy overwrites the first one.

File f = new File(FILE_DIR + fileName);

if(f.exists()) {

System.out.print("file already exists");

fileName = "copy_of_" + fileName;

}

Answer

In your class you declare :

private static int X = 0;

and then change the code to this:

File f = new File(FILE_DIR + fileName);

        if(f.exists()) { 

            System.out.print("file already exists");

            fileName = "copy_of_ " + X + fileName;
x++;

        }

so everytime the x will increase by 1, (x++), so they will have different names.

Comments