为什么指定路径有资源,class.getResource() 还是一直返回null?

Why does class.getResource() keep returning null although there is a resource at the specified path?

我想知道为什么方法 getResource 一直返回 null,我有以下设置:

public static URL getResource(String path){
    URL url = ResourceLoader.class.getResource(path);
    if (Parameters.DEBUG){
        System.out.println(path);
    }
    return url;
}

我在Eclipse中的项目结构如下:

-- res
  -- img

我传递给 getResourcepath 变量的值为 "/res/img""/res/img/smile.png"。然而该方法一直返回 null 并且 url 未设置。我还按照 this question 的说明进行操作,即通过 运行 配置 将文件夹添加到项目的 类路径 ,仍然没有成功......有谁知道我做错了什么?

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)

The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResource(java.lang.String). Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

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

简答:使用"/img/smile.png"

实际发生的情况是,任何以 / 开头并提供给 Class.getResource 方法的路径始终被视为相对于类路径中的每个条目。

如您的屏幕截图所示,res 目录就是这样一个类路径条目。因此 Class.getResource 方法将您提供的路径视为相对于该条目的路径。意思是,相对于 res 目录。

因此,该方法将您的字符串参数与该目录相结合,结果为 res/res/img/smile.png。由于该位置不存在文件(资源),因此它 returns 为空。