views:

78

answers:

2

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?

+3  A: 

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.

mdma
@mdma how can I change this to work `private myMethodnew(StreamSource(new File(xmlFile))`
Gandalf StormCrow
gr8 answer what about when I'm writing to files in src/main/resources ?
Gandalf StormCrow
you shouldn't really write files under src at runtime. That directory will only exist during development, not when your file is packaged and deployed. If you want to read and write to files, then use a specific directory. You can find out if a resource corresponds to a file by getting the URL from Class.getResource(), then then converting the URL to a file. See http://weblogs.java.net/blog/2007/04/25/how-convert-javaneturl-javaiofile
mdma
+2  A: 

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

Pangea