Search code examples
javaimagedebuggingpathjar

Path for getClass().getResource(path) in debug mode


I have such piece of code

private Image createImage(String path)
{
    URL imageURL = getClass().getResource(path);

    if (imageURL == null)
    {
        System.err.println("Resource not found: " + path);
        return null;
    }
    else
    {
        return (new ImageIcon(imageURL)).getImage();
    }
}

When I run app using jar file, the path for getResource() is set to /data/ico.png and because inside the jar ico.png file located in app.jar/data/ico.png everything is OK and image is created.
However when I try to debug it with IDE I pass an argument to app isdebug based on I change the path to ..\\..\\..\\data\\ico.png. As a result I don't find ico.png.
Can I even use getResource() in this way or I just miss the png file?
Or maybe there is some common and better way to do such things like pathes in jar/debug modes?
Dir structure is

src.packageA.packageB.MainClass.java

and ico.png is located inside

data\ico.png

===solution===
I figured out the proper path for my structure is ../../../data/ico.png (or shortly /data/ico.png). In this configuration data/ico.png for MyClass.class.getResource() has to be located in bin.
This is important info because during launching in debug mode for Eclipse root folder is not a project one but bin.


Solution

  • .. - no. However, getResource allows you to start off with a slash which means the resource is looked for relative to the root of that classpath entry. For example, if you have in a jar this structure:

    mypkg/MyClass.class
    mypkg/icons/icon1.png
    logos/logo1.png
    

    (i.e. that is what you see when you run jar tvf myjar.jar), then you can access all of that:

    MyClass.class.getResource("icons/icon1.png");
    MyClass.class.getResource("/mypkg/icons/icon1.png");
    MyClass.class.getResource("/mypkg/logos/logo1.png");
    

    A few notes:

    • getClass().getResource() is wrong. MyClass.class.getResource() is correct. getClass() breaks when you subclass. Even if you don't, it's not good to write fragile code.
    • You do not ever use backslashes here. That's a windows thing and thus irrelevant - (even if you run your java app on windows, you'd use forward slashes. The thing you pass to getResource is a resource identifier, not a path. It's the same reason .. is not okay in there).