Reputation: 29
I can't seem to get my head around accessing resource files, when the resources-marked folder 'resources' is not inside the source-marked folder 'java'.
Here is my project structure (which follows Maven structure, but I still like it):
|src
|-main
|--java (marked as sources folder)
|--|projectname
|--|-main.java
|--|-Class2.java
|--|- ..
|--|-Classx.java
|--resources (marked as resources folder)
|--|config.properties
|--|images
this is how it looks in IntelliJ
I have applied every possible change to the following line, still I can't seem to load the config.properties file or any other file from the resources folder.
getClass().getResource("config.properties");
which is being called in the main class. This should be working right? Why doesn't it though?
How do I access a resource with this project structure?
Much love, Jiefu
edit 1: after same testing, it seems to have to do with directories being between the marked source folder and the content root (which is parent of src here) I don't yet know why this is or how to get around it...
Solved: turns out, deleting the output folder and restarting IntelliJ fixes it. I had to do it twice though... Weird.
I was wrapping my head for two days about this and this is what it was ^.^
Upvotes: 3
Views: 4745
Reputation: 159086
Your class is in package projectname
, so the code is looking for the resource file projectname/config.properties
, but the file is not there.
To look for resource file config.properties
, use:
getClass().getResource("/config.properties");
as documented in the javadoc of getResource()
.
And remember, the resource may not be a file on the file system, so don't use e.g. File
to access it. To read the content of the resource, use getResourceAsStream()
instead.
Upvotes: 3