How to access an image from within a JAR
I know this question (or similar ones) has been asked before, but I still don't understand it. I've created a jar that has the following internal structure:
JAR file
-configuration
---codeBehind
---commandLine
---gui
---resources
Within the resources folder, I have an image that I'd lik开发者_JAVA技巧e to use as an icon, but I can't figure out how to get it. I've tried
ImageIcon icon = new ImageIcon(getClass().getResource("settings.png"));
setIconImage(icon.getImage());
but it throws a NullPointerException
when I tried to access the image of the icon. I tried to separate the pieces of the command, and getResources("mypic.png")
returned null.
Any ideas on how I can get it? Thanks in advance!
From the documentation of Class:
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form: modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
So you probably want
getResource("/settings.png")
or
getResource("/resources/settings.png")
or something similar, depending on your classpath, I believe.
getClass().getResource() will look for a resource with the specified name starting from (relative to) the package the class on which you call getClass() is called.
if you want the resource relative from the root of the jar, then you should do getClass().getClassLoader().getResource()
If you do not want to mess with the classpath and anyway, in any case, there's an overkill but 100% foolproof method that works that is based on the two following facts:
it is always possible to find where the .jar that your class was (class)loaded from is located
a .jar file is simply a zip file and Java has a default API allowing to read zip files.
It is overkill, but it "Just Works [TM]" (and due to various guarantees made by Java it cannot not work: you can always find the path to a .jar and always read from that .jar) and is convenient when you want to create a unique .jar that can be launched as is on Windows, OS X, Linux, etc.
We're using this overkill method on an app that is deployed on hundreds of different systems.
精彩评论