detecting a file downloaded in selenium java detecting a file downloaded in selenium java selenium selenium

detecting a file downloaded in selenium java


I had the same question and here is what I found somewhere on the Internet (maybe on stackoverflow, I cannot remember). I just added a line to delete the file so that by calling this method at the beginning of my test, I'm making sure the file does not exist anymore when trying to download it again.

  public boolean isFileDownloaded(String downloadPath, String fileName) {  File dir = new File(downloadPath);  File[] dirContents = dir.listFiles();  for (int i = 0; i < dirContents.length; i++) {      if (dirContents[i].getName().equals(fileName)) {          // File has been found, it can now be deleted:          dirContents[i].delete();          return true;      }          }      return false;  }

You just have to call with this single line:isFileDownloaded("C:\Path\To\Your\Folder", "yourPdfFile.abc");

Hope this helps!


My solution in the end was to count the files in the download directory before and after i open the page.

I'll be glad to know if someone knows a way to find the trigger for the download


I am handling a similar condition in my automation.

Step1: set the download path in chrome using chrome preference

ChromeOptions options = new ChromeOptions();HashMap<String, Object> chromePref = new HashMap<>();chromePref.put("download.default_directory", <Directory to download file>);options.setExperimentalOption("prefs", chromePref);

Make sure that there is no file with the expected file name in the folder where you are downloading.

Step 2: navigate to the url in chrome, the file will be automatically downloaded to the specified folder.

Step 3: check the file existence in the downloaded folder.