簡體   English   中英

如何使用java-selenium webdriver檢查zip文件是否成功下載?

[英]How to check whether a zip file is successfully downloaded or not using java-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個字節。

這是我管理下載文件的方式:

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

取兩個字符串列表:

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列表,你可以輕松地比較它。 雖然它不會檢查文件大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM