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.
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()); defaultProps.load(in); in.close(); properties = new Properties(defaultProps);
Getting an image:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource(filename));