【问题标题】:how to download a file inside Java project's resource directory如何在 Java 项目的资源目录中下载文件
【发布时间】:2017-02-27 15:06:20
【问题描述】:

我有一个场景,我在我的应用程序中单击下载链接,它会在我的本地驱动器中下载一个 Excel 表。我正在使用 selenium webdriver 来自动化和验证文件是否确实已下载。我能够下载文件并验证它在本地文件系统中的存在。但是如何在我的项目的资源目录中制作webdriver下载文件。

这就是我现在正在做的事情:

System.setProperty("webdriver.chrome.driver", Constants.Chrome_Driver_Path_Win);
            HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
            chromePrefs.put("profile.default_content_settings.popups", 0);
            chromePrefs.put("download.default_directory", "C:\\pixeldownload");
            ChromeOptions options = new ChromeOptions();
            options.setExperimentalOption("prefs", chromePrefs);
            DesiredCapabilities cap = DesiredCapabilities.chrome();
            cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
            cap.setCapability(ChromeOptions.CAPABILITY, options);
            driver = new ChromeDriver(cap);

现在我正在对“C:\pixeldownload”进行硬编码,但我想将文件放入我的 java 项目中的“resource”文件夹中。

chromePrefs.put("download.default_directory", "resource").将目的地作为“资源”对我没有帮助。我如何在“资源”目录中下载文件。

public boolean isFileDownloaded(String downloadPath,String fileName) {
        boolean flag = false;
        File dir = new File(System.getProperty("user.dir") + "\\resources\\downloads");
        File[] dir_contents = dir.listFiles();
        for (int i = 0; i < dir_contents.length; i++) {
            if (dir_contents[0].getName().contains(fileName))   
                return flag=true;   
                }
        return flag;
    }

【问题讨论】:

    标签: java excel selenium-webdriver


    【解决方案1】:

    如果你想下载文件到你的测试资源目录试试这个:

    String downloadDir = System.getProperty("user.dir") + "\\src\\test\\resources";
    
    chromePrefs.put("download.default_directory", downloadDir);
    

    我在我的项目中使用它。

    【讨论】:

    • 谢谢@baadnews,它现在正在工作。有没有办法在脚本的帮助下验证文件是否真的在那里下载?我正在使用类似的东西,但是当我用“System.getProperty(“user.dir”)+“\\src\\test\\resources”替换下载路径时。我在原始帖子中附加了方法。
    • 如果这个问题太多了,我会创建一个单独的线程。
    • 反斜杠与正斜杠的使用可能取决于系统。可以改用System.getProperty("path.separator");
    • 感谢@GrzegorzGórkiewicz
    • 要验证文件是否存在,您可以使用 java.nio.file.Files 中的方法 - exists() 例如。 Path path = Paths.get(filePathString);return Files.exists(path);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多