I have a maven module with the following directory structure and I want to get the path to abc.access
in abcManager.java.
src
|-main
|-java
|-org.abc.xyz
|-init
|-abcManager.java
|-resources
|-abc.access
I tried it using abcManager.class.getResource("abc.access")
but it gives a null.
I went through the below questions but the solutions didn't work.
How to get the path of src/test/resources directory in JUnit?
Can't get path to resource
Java creating file with FilesPath path = Paths. get("src/main/resources/myfile. txt"); A Path object is created.
src/main/resources – configuration files and others such as i18n files, per-environment configuration files, and XML configurations. src/main/webapp – for web applications, contains resources like JavaScript, CSS, HTML files, view templates, and images.
The problem was that I have not included the resource in the maven build in pom file. When I included the following it worked with abcManager.class.getResource("/abc.access")
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>abc.access</include>
</includes>
</resource>
</resources>
</build>
According to the javadoc of URL java.lang.Class.getResource(String name)
:
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
- If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise,the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
When you invoke :
abcManager.class.getResource("abc.access")
You don't prefix the path with a "/"
character . So, you use the second way.
It means that the resource should be located in
the org.abc.xyz.init
package (or folder) but it is not the case since the resource is located in the root of the resources
folder.
In Maven, resources
is the base directory for resources.
So you can get the resource by invoking the first way:
abcManager.class.getResource("/abc.access")
or you can also simply do it :
getClass().getResource("/abc.access")
try this :
String filename = "abc.access";
InputStream in = getClass().getClassLoader().getResourceAsStream(filename);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With