Correctly loading resources (images and files) in Java

To load a file (be it a text file or image) in Java is fairly easy, and most of the time all you need if the path to the resource. However, the filename approach does not work so well when your data is inside a JAR file. JAR files are basically ZIP with a different extension, and a regular filename don’t make sense when the resources are inside the jar.

This is a pretty common problem that many developers face when their app goes into production (including Swing apps), because when they are developing all files are exploded (e.g., not inside a jar), and thus loading images and files using paths like the example below work fine

// This will work when your app and resources
// are not contained inside a jar
String path = getClass().getResource("/path/to/image.jpg").getFile();
Image image = new ImageIcon(path).getImage();

Note the call to getFile(). However, getFile() will return invalid paths once you pack your application, resulting in errors.

In order to make it work right, you should use the getResource() method of Class (or getResourceAsStream()) without the call to getFile(), and instead use the URL or Stream directly. The previous example will then be converted to

// ImageIcon, like many others, can receive an URL as argument,
// which is a better approach to load resources that are
// contained in the classpath
URL url = getClass().getResource("/path/to/image.jpg");
Image image = new ImageIcon(url).getImage();

The very same approach works for files, but instead you’ll use getResourceAsStream().

One thought on “Correctly loading resources (images and files) in Java

Leave a Reply

Your email address will not be published. Required fields are marked *

7 - four =