Vivek Bhardwaj
Vivek Bhardwaj

Reputation: 25

Java: How to copy a file in a directory if there exists a file with same name already

I have created an automation script in java that takes a screenshot after every action and saves it in a directory, however the name of the screenshot is a variable (it's the name of the link I am testing). So, it is possible that the screenshot already exists in that directory.

If there is already a file named xyz.png and I am trying to save a screenshot with the same name I want it to be saved as xyz(1).png and not replace the existing xyz.png.

Here is the script I am using:

  File scrFile = ((TakesScreenshot)cd).getScreenshotAs(OutputType.FILE);

  FileUtils.copyFile(scrFile, new File("C:\\saved_screenshots\\"+ScreenshotName+".png"));

Upvotes: 1

Views: 3743

Answers (3)

shan1024
shan1024

Reputation: 1399

You can do it like this:

File destinationFile = new File("C:\\saved_screenshots\\"+ScreenshotName+".png");//Create the destination file

//if the destination file already exists, add (1) to the end of the file name. Else copy the scrFile to destinationFile
if(destinationFile.exists()){
    int count=1;
    while(true){
        File tempFile = new File("C:\\saved_screenshots\\"+ScreenshotName+"("+count+").png");
        if(!tempFile.exists()){
            break;
        }else{
            count++;
        }
    }
    FileUtils.copyFile(scrFile, new File("C:\\saved_screenshots\\"+ScreenshotName+"("+count+").png"));
}else{
    FileUtils.copyFile(scrFile, destinationFile));
}

Upvotes: 1

JVon
JVon

Reputation: 694

This should put you on the right track:

File scrFile = ((TakesScreenshot) cd).getScreenshotAs(OutputType.FILE);
String desiredName = "C:\\saved_screenshots\\" + ScreenshotName + ".png";
File dstFile = new File(desiredName);
int i = 0;
while (dstFile.exists ()) {
    i += 1;
    desiredName = "C:\\saved_screenshots\\" + ScreenshotName + " (" + i + ").png";
    dstFile = new File(desiredName);
}
FileUtils.copyFile (scrFile, dstFile);

Basically, if a file exists, increase a counter (which changes the destination file name) until the name is available.

Upvotes: 0

Raman Shrivastava
Raman Shrivastava

Reputation: 2953

use File.exists() to check if file by that name already exists.

Upvotes: 1

Related Questions