views:

140

answers:

4

I have a jar file with resources (mainly configuration for caches, logging, etc) that I want to distribute.

I'm having a problem with the relative paths for those resources, so I did what I've found in another stackoverflow question, which said that this was a valid way:

ClassInTheSamePackageOfTheResource.class.getResourceAsStream('resource.xml');

Sadly this does not work.

Any ideas? Thanks!

PS: Obviously I cannot use absolute paths, and I'd like to avoid environment variables if possible

+1  A: 

I always have to puzzle through getResourceAsStream to make this work. If "resource.xml" is in org/pablo/opus, I think you want this:

Name.class.getResourceAsStream("org.pablo.opus.resource.xml");
trashgod
+1  A: 

where the resource.xml found? If in the root of the source tree, try to prefix it with /.

Seffi
It's not on the root of the source tree. It's inside a package
Pablo Fernandez
so treat the fully qualified name as an absolute path, for example com.me.and.u.effects.css would be accessed as /com/me/and/u/effects.css
Seffi
+1  A: 

I usually store files and other resources and then retrieve them as URLs:

URL url = MyClass.class.getResource("/design/someResource.png");

Within a static context, or otherwise:

URL url = getClass().getResource("/design/someResource.png");

From an instance.

The above snippets assume that design is a top level folder within the jar. In general, if the path begins with a "/" it assumes an absolute path, otherwise it's relative from the class location.

Jason Nichols
+3  A: 

Make sure that your resource folder is listed as a source folder in your project settings. Also, make sure that the resource folder is set to export when you build your jar.

You can add a .zip extension to your jar file then open it up to ensure that your resources are included and at the expected location.

I always use absolute paths like this:

InputStream input = this.getClass().getResourceAsStream("/image.gif");

When you use absolute paths, "/" is the root folder in the jar file, not the root folder of the host machine.

Marcus Adams
+1 for the note about / being the jar's root folder.
R. Bemrose
Indeed, I used the (jar) absolute path method you described and it worked! Don't know why it didn't do the trick with the relative one... but good enough is good enough
Pablo Fernandez