gpt4 book ai didi

java - 为什么class.getResource()在指定路径下有资源却一直返回null?

转载 作者:搜寻专家 更新时间:2023-10-31 19:54:34 26 4
gpt4 key购买 nike

我想知道为什么 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/微笑.png”。然而该方法一直返回 null 并且 url 未设置。我也按照 this question 的说明进行操作,这是通过运行配置将文件夹添加到项目的类路径,仍然没有成功...有人知道我做错了什么吗?

enter image description here

最佳答案

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

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

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

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

关于java - 为什么class.getResource()在指定路径下有资源却一直返回null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219224/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com