Reputation: 16233
I have a maven project with this structure:
parent
-----module1
--------src
------------main
-----------------java
----------------------Loader.java
-----------------resources
-------------------------file1.txt
-----module2
--------src
------------main
-----------------java
-------------------------CallLoader.java
So Loader.java
, loads files1.txt
. I call this class from CallLoader.java
from module2. This is the code I used
In Loader.java
,
private static File getResourceFile(String fileName){
try {
URL resource = GraphUtil.class.getClassLoader().getResource(fileName);
return new File(resource.getPath());
} catch (Throwable e) {
throw new RuntimeException("Couldn't load resource: "+fileName, e);
}
}
where fileName="file1.txt"
.
I get an error because the file absolute path looks like this:
file:/home/moha/.m2/repository/my/package/name/%7Bproject.version%7D/base-%7Bproject.version%7D.jar!/file1.txt
What exactly am I doing wrong?
Upvotes: 1
Views: 65
Reputation: 44965
Get the content of your file as a stream instead in order to be able to read your resource from a jar file which is the root cause of your issue. In other words use getResourceAsStream
instead of getResource
.
You can also return the URL
instead of File
then call openStream()
later to read it if needed.
NB1:
the URL will be of type jar:file/...
which cannot be managed by the class File
NB2:
To convert a URL
into a File
, the correct code is new File(resource.toURI())
Upvotes: 2