如何使用Java-Selenium WebDriver检查zip文件是否已成功下载?

时间:2019-05-28 06:12:07

标签: java selenium selenium-webdriver

我正在从一个应用程序下载多个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个字节。

2 个答案:

答案 0 :(得分:2)

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

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;
      }
}

答案 1 :(得分:1)

获取两个字符串列表:

List<String> expectedFileName ;

在此列表中添加您必须具有字符串格式的每个文件名。[您期望的文件名]

然后下载所有文件,然后转到下载目录:

使用以下代码检查存在多少文件:

new File(<directory path>).list().length

现在比较预期长度和实际长度:

expectedFileName.size()new File(<directory path>).list().length,如果存在任何不匹配,则返回 false 并打印文件丢失。如果没有任何不匹配,则获取像这样的目录中的所有文件名:

List<String> actualFileName;
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
   actualFileName.add(listOfFiles[i].getName());
}
} 

现在您有两个String列表,可以轻松进行比较。虽然它不会检查文件大小。

相关问题