Opening files using selenium WebDriver when it's in the resources folder in a maven project

时间:2018-04-18 18:18:06

标签: java selenium selenium-webdriver cucumber

I'm trying to open different types of files using webdriver(.txt and pdf). So I have the files in the resources folder but when I open them I get the following error message: malformed exception

But if I open the file from my desktop it works perfectly fine:

So for example this is what I have:

 String file_loc = logInPage.getFile(file_name);
    logInPage.navigateToFileLoc(file_location);

These are the implementation of the two methods

 public String getFile(String fileName) {

        String result = "";

        ClassLoader classLoader = getClass().getClassLoader();
        try {
            result = IOUtils.toString(classLoader.getResourceAsStream(fileName), java.nio.charset.StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

public void navigateToFileLoc(String fileLoc){
   webDriver.get(fileLoc);
}

But when I try to get the file from the desktop it works perfectly fine: For example webDriver.get("file:///C:/Users/test.pdf")

It's like as if you are trying to open a pdf or html in an IDE

1 个答案:

答案 0 :(得分:1)

请按照以下步骤更改 getFile 方法:

public String getFile(String fileName) {
        String filePath = null;
        ClassLoader classLoader = getClass().getClassLoader();
        try {
            filePath= classLoader.getResource(fileName).getPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  "file://"+filePath;
    }