'How to wait until file is downloaded and also wait until the file is deleted from folder in Selenium Java

Have to download a file in multiple formats xls, pdf, rtf, csv, txt. But I have to check all these file formats are downloaded one after another

So I have written below code which gets executed after Download button is clicked. But I want the system to wait until the file is downloaded completely and also wait until the file is deleted from folder. Only after file is deleted I want to click Download button again

File dir = new File(folderPath);
dirContents = dir.listFiles();
int dirContentsSize = dirContents.length;

for (int k = 0; k < dirContents.length; k++) 
{
    String fileName = dirContents[k].getName();
    System.out.println(fileName + " identified");
    dirContentsSize = dirContents.length;
    boolean isFileDeleted = dirContents[k].delete();
    if (isFileDeleted)
    System.out.println(fileName + " successfully deleted file");
}

Kindly help



Solution 1:[1]

The following code which involves do while is working fine where it checks if the file is not directory and file names doesn't contain temporary filename crdownload prior to deleting the file. Before the delete file command is executed it keeps on checking for the above 2 conditions.

                    do {
                        for (File file : dir.listFiles()) {
                            
                            if (!file.isDirectory() && !file.getName().contains("crdownload")) {
                                Thread.sleep(100);
                                file.delete();
                                System.out.println(reportName + " " + file.getName() + " deleted successfully");
                            }
                        }    
                    } while (dir.listFiles().length != 0);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sreedhar Danturthi