Take Screenshot using FileHandler class in Selenium

Until today, we have used below code snippet in our automation scripts to take the screenshot using selenium. But most of them started complaining about FileUtils which was working fine earlier, but is not working after upgrading selenium webdriver with latest version.

File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:/reports/screenshot.png"), true);

FileUtils.copyFile throws error as 'FileUtils cannot be resolved' error with selenium webdriver because selenium was using a dependency to commons-io, but latest versions of Selenium is not using.

Selenium fileHandler class

If you see an error and want to fix that, then you should update your pom.xml to include commons-io directly instead of getting it transitively through Selenium.

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

In other way, selenium webdriver provides FileHandler class to achive the same. Below is the syntax for it :

public static void copy(java.io.File from, java.io.File to) throws java.io.IOException

FileHandler class which extends java.lang.Object is used to perform different I/O actions using webdriver. WebDriver provides utility methods for common filesystem activities with FileHandler class.

Let us look at the below example for taking screenshot using selenium webdriver FileHandler class -

public class getScreenShot() {
      try {
            File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            //The below method will save the screen shot in destination directory with name "screenshot.png"
             FileHandler.copy(scrFile, new File("D:/reports/screenshot.png"));
         } catch (IOException e) {
             e.printStackTrace();
            }
  }

The copy()method will copy the screenshot to the destination directory. If you observe the above example, the only change which we have done is

FileHandler.copy(scrFile, new File("D:/reports/screenshot.png"));

. If the path specified is not valid, it will throw IOException.

There was a case were user was complaing that It was working fine in local machine, even after updating selenium version to latest. But if you check .m2 repository folder, you should already have commons-io and import statement import 'org.apache.commons.io.FileUtils' as well.

Selenium Tutorials: 

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.