1.设置谷歌浏览器的下载路径,代码如下
public static WebDriver setDownloadsPath() {
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("download.default_directory", downloadsPath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(caps);
return driver;
}
2.获取下载的文件名,代码如下
public static String getDownloadedDocumentName(String filepath, String filename)
{
String downloadedFileName = null;
boolean valid = true;
boolean found = false;
//default timeout in seconds
long timeOut = 30;
try
{
Path downloadFolderPath = Paths.get(filepath);
WatchService watchService = FileSystems.getDefault().newWatchService();
downloadFolderPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
long startTime = System.currentTimeMillis();
do
{
WatchKey watchKey;
watchKey = watchService.poll(timeOut,TimeUnit.SECONDS);
long currentTime = (System.currentTimeMillis()-startTime)/1000;
if(currentTime>timeOut)
{
System.out.println("Download operation timed out.. Expected file was not downloaded");
return downloadedFileName;
}
for (WatchEvent<?> event: watchKey.pollEvents())
{
WatchEvent.Kind<?> kind = event.kind();
if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE))
{
String fileName = event.context().toString();
System.out.println("New File Created:" + fileName);
if(fileName.endsWith(filename))
{
downloadedFileName = fileName;
System.out.println("Downloaded file found with extension " + filename + ". File name is " +
fileName);
Thread.sleep(500);
found = true;
break;
}
}
}
if(found)
{
return downloadedFileName;
}
else
{
currentTime = (System.currentTimeMillis()-startTime)/1000;
if(currentTime>timeOut)
{
System.out.println("Failed to download expected file");
return downloadedFileName;
}
valid = watchKey.reset();
}
} while (valid);
}
catch (InterruptedException e)
{
System.out.println("Interrupted error - " + e.getMessage());
e.printStackTrace();
}
catch (NullPointerException e)
{
System.out.println("Download operation timed out.. Expected file was not downloaded");
}
catch (Exception e)
{
System.out.println("Error occured - " + e.getMessage());
e.printStackTrace();
}
return downloadedFileName;
}
调用该方法如下
String fileName = getDownloadedDocumentName(downloadsPath,".xlsx");
3.判断指定文件夹下是否存在下载的文件,代码如下
private static Boolean isFileDownloaded_Ext(String filepath, String filename) {
boolean flag=false;
File dir = new File(filepath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
flag = false;
}
for (int i = 0; i <files.length; i++) {
if(files[i].getName().contains(filename)) {
flag=true;
}
}
return flag;
}
调用该方法如下
Boolean bt=isFileDownloaded_Ext(downloadsPath,fileName);