Search code examples
javaintellij-idearelative-pathintellij-14

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.

structure

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


Solution

  • try something like this.

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