I’m consolidating and correcting the code from my first java project, but I’ve hit a wall: I can’t seem to load images relative to where the program is executed. I know this may seem noobish yet I’m eager to fix this and share my projects with the community. http://pastebin.ca/2118804 is a snippet of the code in question, which is within a ‘move()’ class that is executed every five seconds (or micro-seconds). The code, as it stands, gives me a null pointer exception.
This is how i do it:
BufferedImage imgSheet;
void init(){
try {
imgSheet = ImageIO.read(new File(location));
} catch (IOException e) {
System.out.println("Error while loading image sheet! \n Program will now abort.");
e.printStackTrace();
}
}
Where location is a string, and defined in my constructor.
Try that.
Don’t use File if the resource will be in a JAR. It is best to just get a URL:
BufferedImage img = ImageIO.read(<ClassName>.class.getClassLoader().getResource("path/to/resource"));
The path is relative to the root of your project (your “bin” folder in Eclipse, or the root of the JAR).
Thank you for the advice!
[quote]BufferedImage img = ImageIO.read(.class.getClassLoader().getResource(“path/to/resource”));
[/quote]
Wrong. Use this instead:
BufferedImage img = ImageIO.read(getClass().getResource("/path/to/resource"));
getClassLoader() does not work in unsigned applets – this is the main reason that Class has the delegated getResource() method in the first place. Once you’re no longer using getClassLoader directly, you need to write your absolute resource paths as an absolute path, or it will be relative to the package of the class. And since you’re no longer relative to any package, you don’t need to hardwire the class name in.
getClassLoader works for me in unsigned applets…
But I agree with using getClass() over hard-wiring the class name. However, using getClassLoader().getResourceAsStream allows you to skip the delegation in Class.getResourceAsStream where it has to remove the initial forward slash before forwarding to the ClassLoader.
EDIT: According to Class’s source, it always delegates to the ClassLoader anyway. The only time it doesn’t is if the ClassLoader is null, which only occurs if it’s a system class. There it just calls the static method ClassLoader.getSystemResource(path).