Reputation: 26192
I'm reading a few files in my application and referring to them as new File("src/main/resource/filename")
and it works. But when I package the jar with the Maven assembly plugin and run java - jar
I get an error, naturally:
Error occured:
src\main\resources\UPDATE.txt
(The system cannot find the path specified)
Because there is no src/main/resources
in the jar, how can I refer to src/main/resources
as some kind of classpath variable, so that the application works both in standalone java and in an assembled jar?
Upvotes: 1
Views: 649
Reputation: 57707
You will need to load the file using the Class.getResourceAsStream() method
E.g.
InputStream str = getClass().getResourceAsStream("/UPDATE.txt");
Or if you are in a static method, then specify the class explicitly
InputStream str = MyApp.class.getResourceAsStream("/UPDATE.txt");
EDIT:
With a StreamSource
, just pass the input stream into the stream source, e.g.
new StreamSource(getClass().getResourceAsStream("/UPDATE.txt"));
But watch out, getResourceAsStream returns null if the resource doesn't exist, so you might want to explicitly check for that and throw an exception.
Upvotes: 3
Reputation: 80166
The src/main/resources is a development time convention followed by maven projects to place artifacts other than source code. Once the jar has been build they are added to the classpath. So in your e.g. scenario the UPDATE.TXT is at the root of the classpath.
So you should be referring to the resources from the classpath and not from the file-system. http://mindprod.com/jgloss/getresourceasstream.html
Upvotes: 2