首页 > 解决方案 > 如何使用 java-selenium webdriver 检查 zip 文件是否已成功下载?

问题描述

我正在从一个应用程序下载多个 zip 文件,每个文件都有不同的大小。显然,下载时间取决于文件大小。我有下面的java代码来根据文件大小检查下载。但它没有按预期工作。它只是等待10秒并通过继续下一组行来终止循环。有人可以帮我解决这个问题吗?

public void isFileDownloaded(String downloadPath, String folderName) {

        String source = "downloadPath" + folderName + ".zip";

        long fileSize1;
        long fileSize2;
        do {
            System.out.println("Entered do-while loop to check if file is downloaded successfully");

            String tempFile = source + "crdownload";
            fileSize1 = tempFile.length(); // check file size
            System.out.println("file size before wait time: " + fileSize1 + " Bytes");
            Thread.sleep(10); // wait for 10 seconds
            fileSize2 = tempFile.length(); // check file size again
            System.out.println("file size after wait time: " + fileSize2 + " Bytes");

        } while (fileSize2 != fileSize1);

        }

等待时间前后的 fileSize 始终返回 43 个字节。

标签: javaseleniumselenium-webdriver

解决方案


这是我管理下载文件的方式:

public class Rahul {

    String downloadDir = "C:\\Users\\pburgr\\Downloads\\";

    public WebDriverWait waitSec(WebDriver driver, int sec) {
        return new WebDriverWait(driver, sec);
    }

    public File waitToDownloadFile(WebDriver driver, int sec, String fileName) {
        String filePath = downloadDir + fileName;
        waitSec(driver, 30).until(new Function<WebDriver, Boolean>() {
          public Boolean apply(WebDriver driver) {
            if (Files.exists(Paths.get(filePath))) {
              System.out.println("Downloading " + filePath + " finished.");
              return true;
            } else {
              try {
                Thread.sleep(1000);
              } catch (InterruptedException e) {
                 System.out.println("Downloading " + filePath + " not finished yet.");
              }
            }
            return false;
          }
        });
        File downloadedFile = new File(filePath);
        return downloadedFile;
      }
}

推荐阅读