getClass().getResource(resourcePath) valid on windows, null on Linux

elect picture elect · Feb 9, 2014 · Viewed 9.6k times · Source

I have a problem, this call

URL fileURL = getClass().getResource(resourcePath);

works on Windows (7 64b) but not on linux (Ubuntu 13.10 64b) where it returns null.

Why? File is there and the string is the following (relative path)

String resourcePath = "/tut01/shaders/vertex_shader.glsl"

Both file are in my home

Edit: The project was freshly cloned and I forgot to clean & build, sorry for that.. So now it founds them. However it is strange because even if I modify, let's say, the vertex_shader.glsl, my program will refer always to the old version, every time I edit it, I need to do clean & build in order to see the changes... Why? On windows I don't have to do that..

Answer

eclipse-pmd picture eclipse-pmd · Feb 9, 2014

Your resource path starts with a / and is therefore an absolute path. If you want the resource path to be relative you have to omit the first /.

From the Javadoc of Class.getResource(String name):

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.

Otherwise, the absolute name is of the following form: modified_package_name/name where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

A relative path is relative to the path of the class returned by getClass().

An example:

package org.example;

public class MyClass {
    public void foo() {
        getClass().getResource("tut01/shaders/vertex_shader.glsl");
    }
}

Let's assume the compiler writes the compiled class file to /home/my-project/bin/org/example/MyClass.class.

getClass().getResource("tut01/shaders/vertex_shader.glsl") would then look for the file in /home/my-project/bin/org/example/tut01/shaders/vertex_shader.glsl.