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

隐身守侯 提交于 2020-01-14 10:25:10

问题


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..


回答1:


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.




回答2:


Seems you donot have read access to resourcePath location Try putting value in resourcePath which you have access to i.e. you should be able to see the file




回答3:


Check if the Linux account running your Java program has all the necessary
permissions (for the file and the folders on the file path). If the file is indeed
there, then permissions could be the issue.



来源:https://stackoverflow.com/questions/21658061/getclass-getresourceresourcepath-valid-on-windows-null-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!