【问题标题】:Why does class.getResource() keep returning null although there is a resource at the specified path?为什么 class.getResource() 一直返回 null,尽管在指定路径上有资源?
【发布时间】:2023-03-18 04:58:01
【问题描述】:

我想知道为什么方法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"。然而,该方法不断返回 nullurl 未设置。我也按照this question 的说明,通过运行配置将文件夹添加到项目的classpath,仍然没有成功...有谁知道我是什么做错了吗?

【问题讨论】:

    标签: java eclipse class getresource


    【解决方案1】:

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

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

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

    因此,该方法将您的字符串参数与该目录相结合,从而产生res/res/img/smile.png。由于该位置不存在文件(资源),因此它返回 null。

    【讨论】:

    • 很好的解释! :)
    【解决方案2】:

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

    搜索与给定类相关的资源的规则是 由类的定义类加载器实现。这种方法 委托给这个对象的类加载器。如果这个对象是由 引导类加载器,该方法委托给 ClassLoader.getSystemResource(java.lang.String)。在委托之前,一个 绝对资源名称由给定的资源名称构成 使用这个算法:

    如果名称以'/'('\u002f')开头,则绝对名称 资源是名称中“/”之后的部分。

    否则,绝对名称的格式如下: modified_pa​​ckage_name/name 其中 modified_pa​​ckage_name 是 此对象的包名称,用“/”替换“。” ('\u002e')。

    【讨论】:

    • 感谢您的回复!所以,如果理解正确,在我的情况下,以下适用:If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'. 但为什么这不是有效的资源呢?
    • 最容易理解的方法是使用 getResource("") 和一个空字符串。这将为您提供您的班级所在包的 URL。然后只需将该 URL 系统输出,您就会明白。
    猜你喜欢
    • 2014-03-01
    • 1970-01-01
    • 2013-03-12
    • 2012-01-13
    相关资源
    最近更新 更多