在文件下载完成之前不要关闭浏览器



我在Java中有一个下面的场景,需要自动化。

在网页上,输入值后有一个导出到Excel按钮。单击导出按钮后,我需要等待导出完成。我的浏览器不应该被关闭,直到导出完成。注意:导出完成后,不会显示任何消息,因此不确定如何处理。

请帮助处理上面的逻辑。

如果事先知道下载位置和文件路径可以使用下面的方法,

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
return true;
}
}
return false;
}

上面的方法应该根据文件夹中文件的存在返回一个布尔值。

所以你可以有一个逻辑,如果这个方法返回true,这意味着文件在那里,所以现在你可以关闭浏览器会话。如果返回false,则不要关闭会话,等待一段时间后再检查。

更新:

boolean check = CommonMethods.isFileDownloaded(System.getProperty("user.dir") + "\exportedFiles", "My file name here"); 
while(true){
Thread.sleep(1000);
check = CommonMethods.isFileDownloaded(System.getProperty("user.dir") + "\exportedFiles", "My file name here"); 
if(check) {
System.out.println("File available");
break;
}
}

假设文件需要30秒才能下载。同时,我们需要不断检查目录,以确保文件是否被下载。因此,这里我们必须为检查传递一个时间输入。

在下面的代码中,我将waitTillSeconds的值设置为30 seconds,这意味着它将连续检查目录长达30秒。如果在15 seconds处找到该文件,则它将boolean值返回为true,并跳过剩余的15 seconds

public boolean isFileAvailable(String downloadPath, String fileName) {
int waitTillSeconds = 30;
boolean fileDownloaded = false;
long waitTillTime = Instant.now().getEpochSecond() + waitTillSeconds;
while (Instant.now().getEpochSecond() < waitTillTime) {
File dir = new File(downloadPath);
File[] dirContents = dir.listFiles();
for (int i = 0; i < dirContents.length; i++) {
if (dirContents[i].getName().equals(fileName)) {
System.out.println("File downloaded.");
fileDownloaded = true;
break;
}
}
if (fileDownloaded) {
break;
}
}
return fileDownloaded;
}

为什么我们需要给出时间输入?

有时文件可以立即下载,有时需要额外的时间下载基于网速,应用程序慢或其他因素,所以最好给下载的时间。

最新更新