At the beginning of the test create a time stamped folder to save screenshots using the following code:
String scrFolder = "c:/Result/"
+ new SimpleDateFormat("yyyy_MM_dd_HHmmss").format(
Calendar.getInstance().getTime()).toString();
new File(scrFolder).mkdir();
Add the following code after the above code to set an environment variable to point to the screenshot folder:
System.setProperty("scr.folder", scrFolder);
Take screenshot by calling the following method
public static void takeScreenshot(WebDriver driver) throws IOException {
//get the screenshot folder location from enviroment variable set in beginning of test
String scrFolder = System.getProperty("scr.folder");
File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
//copy screenshot to screenshot folder
FileUtils.copyFile(
scrFile,
new File(scrFolder
+ "/screenshot"
+ new SimpleDateFormat("HHmmss").format(
Calendar.getInstance().getTime()).toString()
+ ".png"));
}
Let me know if this helps you.