本文介绍了getClass().getResource(resourcePath)在Windows上有效,在Linux上为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,这个电话

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

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

可以在Windows(7 64b)上运行,但不能在返回null的linux(Ubuntu 13.10 64b)上运行.

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"

两个文件都在我家

该项目是新克隆的,我忘了清理&构建,对此表示抱歉..因此,现在他们找到了.但是,这很奇怪,因为即使我修改了vertex_shader.glsl,我的程序仍将始终引用旧版本,每次编辑它时,我都需要清理&建立以查看更改...为什么?在Windows上,我不必这样做.

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

推荐答案

您的资源路径以/开头,因此是绝对路径.如果您希望资源路径是相对的,则必须省略第一个/.

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

来自 Class.getResource(String name)的Javadoc:

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

否则,绝对名称的格式如下:modified_pa​​ckage_name/name,其中modified_pa​​ckage_name是这个对象的包名用/"代替."('\ u002e').

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

相对路径相对于 getClass()返回的类的路径.

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

一个例子:

package org.example;

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

假设编译器将编译后的类文件写入/home/my-project/bin/org/example/MyClass.class .

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")将在/home/my-project/bin/org/example/tut01中查找文件/shaders/vertex_shader.glsl.

这篇关于getClass().getResource(resourcePath)在Windows上有效,在Linux上为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:49
查看更多