Prabu
Prabu

Reputation: 3728

Selenium using Java.io FileUtils.copyFile to dynamic destination file name

take an screenshot and copy that file in my local folder using java io (Webdriver with Java)

File screenshot = ((TakesScreenshot) driver)
            .getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshot, new File("d:\\pic\\report.jpg"));

i call this method more than one time, so in this situation i dont want to repeat the file name as "report.jpg" so please provide an suggestion how can i change that file name dynamically

like report1 report2 etc.,

Upvotes: 0

Views: 7517

Answers (3)

Algiz
Algiz

Reputation: 1288

A very simple way:

FileUtils.copyFile(screenshot, new File("d:\\pic\\report_" + System.currentTimeMillis() + ".jpg");

I just hope you don't do a screenshot every milliseconds. ;-)

You can improve the readability by using a timestamp.

java.text.SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDD'T'HHMMSSsss");
String newFileName = "d:\\pic\\report_" + sdf.format(new java.util.Date()) + ".jpg";
FileUtils.copyFile(screenshot, newFileName);

Another solution might be to use a static counter in an helper class.

private static int count = 0;
public static void doScreenshot() {
    count++;
    String newFileName = "d:\\pic\\report_" + count + ".jpg";
    FileUtils.copyFile(screenshot, newFileName);
}

Upvotes: 3

rafaborrego
rafaborrego

Reputation: 600

There are many options.

If the suffix number is important:

  • Save in a file or in DB the number of times you have generated it
  • Get the number that contains the name of the last generated file
  • Count the number of images in the folder (not valid it you delete them after a while)

If it is not important:

  • Use a datetime with the current time
  • Use a random number

Upvotes: 1

user1071777
user1071777

Reputation: 1307

You could append the current date and time, or go in a loop checking if the file already exists, appending an number once the file is available.

Date and Time (more meaningful):

Date currDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String dateAndTime = dateFormat.format(currDate);
File reportFile = new File("d:\\pic\\report_" + dateAndTime + ".jpg");
File screenshot = ((TakesScreenshot) driver)
        .getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, reportFile));

Number increment method:

File reportFile;
int number = 0;
do {
    reportFile = new File("d:\\pic\\report" + number + ".jpg");
    number++;
} while (reportFile.exists());
File screenshot = ((TakesScreenshot) driver)
        .getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, reportFile));

Upvotes: 1

Related Questions