We're going to look at loading resources in Java in the Eclipse IDE, though the basic principles are the same in whatever IDE you're using. The general idea is to use the classloader to load your resources rather than using a File object or a FileInputStream. This makes your applications more flexible and relocatable and makes resource loading independent of the current directory. The first thing to do is to create two packages: one as our code package
root and one for resources: 


Our objective is to be able to load the image 'tj-logo.png'. To do that, we'll add a resources package
in the package root: 


Now, unfortunately, in the version of NetBeans show above at least, there's seemingly no method to import resources into the project unless one is using the GUI editor. So we'll copy tj-logo.png into the package directory we just created called 'resources'. Since this is OS-specific, I haven't shown that step here. From now on, we'll assume it's there in ResourceDemo/src/resources. You should be able then to expand the 'resources' node and see something like:


So if we run the app, we should see something like the following, showing that the image
has been found:


The important thing is that when we build our project, the resources should be included in the distribution jar, by default called <project name>.jar, so that our application is relocatable. If we list the jar, we should see the resource(s):


Please support this site using the button below: