David Silva
David Silva

Reputation: 2017

IntelliJ: non absolute (relative) path to resources

I have code like this:

public class EntryPoint {
    public static void main(String args[]) {
        File file = new File("resources/file.xml");
        try {
            Document document = new SAXReader().read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

}

and structure of my test module is as follows:

structure of my test module

The problem is that I get error:

Nested exception: java.io.FileNotFoundException: resources\file.xml

Of course I could change path, for example like this:

File file = new File("C:/ws/_SimpleTests/resources/file.xml");

and it would work ok, but I dont want to use absolute path.

What should I set in IntelliJ to use relative path?

Upvotes: 5

Views: 14360

Answers (2)

SparkOn
SparkOn

Reputation: 8946

First rght-click on the resources folder -> mark directory as -> Resources root then try reading the file this way

InputStream is = TestResources.class.getClassLoader().getResourceAsStream("file.xml");

or

File file = new File(YourClassName.class.getClassLoader().getResource("file.xml")
                                                         .getPath());

Upvotes: 5

sol4me
sol4me

Reputation: 15698

You can use Paths to retrieve file.xml like this

File file = Paths.get(".", "resources", "file.xml").normalize().toFile();

Upvotes: 2

Related Questions