Java: packaging resource files into a runnable jar file

10 steps to package resources files into a jar file without putting the resource files in the source code directory. The example demonstrated here is loading a image file and package it into a runnable jar file, but the same mechanism can be applied to any other resource files such as audio files, property files as well.

1. Create a Java project in Eclipse
2. Create a package main under src package folder
3. Create the Java class in main package

package main;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JFrame;
import resources.ResourceLoader;

public class LoadImage extends JFrame{
	Image img=ResourceLoader.loadImage("java.jpg");
	 public void paint(Graphics g) {
	        g.drawImage(img, 0, 0, null); // see javadoc for more info on the parameters    
	public static void main(String args[])
		LoadImage li = new LoadImage();
		li.setSize(300, 300);

4. Create a package folder res at the same directory level as src and make sure it is included in the build path by right click it->Build Path->Use it as source folder
5. Create packages resources and resources.images inside this res.
6. Create in the resources package

package resources;
import java.awt.Image;
import java.awt.Toolkit;
public class ResourceLoader {

	static ResourceLoader rl = new ResourceLoader();
	public static Image loadImage(String imageName)
		return Toolkit.getDefaultToolkit().getImage(rl.getClass().getResource("images/"+imageName));

7. Put a image java.jpg inside the package resources.images
8. Run the LoadImage main method, it should fired up a JFrame with the image java.jpg
9. Export this project into a runnable jar file by File->Export->Java->Runnable Jar->…..
10. Fire up the jar file, it should open up a JFrame with the image java.jpg

Search within Codexpedia

Custom Search

Search the entire web

Custom Search