Skip to main content
GameDev.net gamedev.net
🔒 Locked

Getting Resources in a Jar File

Started by OscarYang Feb 6, 2012 at 11:33 PM 2 replies 2.7k views
Original Post
OscarYang
OscarYang
While loading any resources in a developing environment (ie run from Eclipse or BlueJ or w/e you use to edit your Java including CMD / Shell), it is easy. You can use relative path or absolute path. However, it seems when I export my game into a jar file, the path is not returned properly even if I call getClass().getResource("/").getPath(). I am GUESSING that it has to do with the fact that my classes (.java files) are inside packages. Specifically, they are in "sf/core/" folder (package sf.core). I have been searching (Google) and have yet to find any solutions. The getResource() always return null and calling getPath() will cause a NullPointerException. Anyone know of this problem?

Thanks,
CXD
Matt328
Matt328
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#getResource(java.lang.String)

I think your problem might be that "/" isn't a valid resource. As per the last few lines of the javadoc linked above, the method returns null when the resource you request isn't found.

getResource() is designed to give you a URL to a resource, and in this context, a folder within a jar file isn't considered a resource. Try putting an image at the root of the classes directory inside the jar file (alongside your 'sf' folder) and see what getResource("image.png") returns.
PsionicTransvection
PsionicTransvection
I also had a similar problem but I managed to fix it here is an example from mi code

ImageIcon X = new ImageIcon(getClass().getResource("/images/X.png"));

my image is stored in src/images/
see how I wrote the string for the path try it out
OscarYang
OscarYang
Thanks for the replies! Eventually I gave up because there is some sort of synchronization problem which "getClass()" doesn't work well. I solved by using a global static string which contains the root path. I made it to work with a jar by basically not including the resources inside the jar file. I explicitly asked for the place where the jar file is located and then load images / sounds / resources from there assuming that the folder will always be there.

I also suspect that "getResource()" doesn't work due to my Eclipse export isn't setup properly. Anyone have any ideas about this?

Thanks,
CXD

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.