Posted by: Josh | September 29, 2008

Accessing resources when packaged as a JAR

I’ve run into this problem in several of my projects, and now I’m going to finally document it. The problem: your project works fine loading images and reading in other assorted files (xml, txt, properties, mp3, for example) but the moment you package it all up into a tidy Java ARchive? Disaster – all your images and whatnot appear to not even be there.

Solution: access the files as a URL or InputStream using the getResource(String filepath) or getResourceAsStream(String filepath)

The String supplied could be something like “/image.jpg”, where that forward slash denotes the top level of the JAR filestructure (you can see this directory structure by opening the JAR in an archive tool such as WinRAR). So if your image was placed inside the JAR a couple directories down, the supplied string should look something like “/com/joshjcarrier/tutorial/image.jpg” .


Getting an input stream of a properties file


Properties defaultProps = new Properties();
URL propFile = getClass().getResource(propertiesFile);
BufferedInputStream in = new BufferedInputStream(propFile.openStream());
properties = new Properties(defaultProps);


Getting an image:

Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource(filename));


  1. Good stuff man!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: