简体   繁体   中英

Unable to get relative path in IntelliJ for resource file - Java/Selenium

I am struggling with getting a relative path to a file in a resource folder. I have spent hours pouring over and attempting other resolutions in other threads, but have failed, I don't know whether due to the exact syntax being wrong, but I would really appreciate some help with exactly what to write. Screenshot is attached

File setup

I run my tests from my class TestRunner which goes to PropertiesUtil to get the browser to run the tests in, from the config.properties file.

The config.properties file is in a resources folder but I am unable to get to the config file using a relative path. It works fine as an absolute, but that means it fails when someone else runs it.

If I do attempt other paths, I get the error:

2019-03-06 21:21:16 INFO  TestRunner - Before running
java.io.FileNotFoundException: config.properties (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)

Please help! I've spent far too long stuck on this.

结构体

Tried with ClassLoader as suggested but this doesn't work in propertiesUtil nor am I quite sure how to write it in conjunction with what I have (as it complained about static/non-static). On running from TestRunner to try and debug and understand, it doesn't give me much useful information. ClassLoader

I also tried a similar thing I saw elsewhere. Same issue: non-static to static error

try something like this.

   public static void readPropertiesFiles() {
        ClassLoader classLoader = PropertiesUtil.class.getClassLoader();
        String path = classLoader.getResource("config.properties").getPath();
        System.out.println(path);
    }

Amazing!! That works brilliantly. For reference to anyone finding this - this is a screenshot of the code now with the above fix!

Working code now implemented

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM