为什么class.getResource()保持返回null,虽然在指定的路径有一个资源? [英] Why does class.getResource() keep returning null although there is a resource at the specified path?

查看:1038
本文介绍了为什么class.getResource()保持返回null,虽然在指定的路径有一个资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wondering why the method getResource keeps returning null, I have the following setup:

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



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

My project structure in Eclipse is as follows:

-- res
  -- img


b $ b

传递给 getResource 路径变量具有值/ res / img/ res / img / smile.png。然而,该方法继续返回 null url 未设置。我也遵循此问题的说明,这是将文件夹添加到项目的通过运行配置,仍然没有成功...有人知道我在做什么吗?

The path variable I pass to getResource has the value "/res/img" or "/res/img/smile.png". Yet the method keeps returning null and url is not set. I also followed the instructions of this question, which were to add the folder to the project's classpath via Run configurations, still without success... Does anyone know what I am doing wrong?

img src =https://i.stack.imgur.com/zU1Vp.pngalt =enter image description here>

推荐答案

简短答案:使用/ img / smile.png

任何以赋给Class.getResource方法的 / 开头的路径总是被视为相对于类路径中的每个条目。

What's actually happening is that any path starting with / which is given to the Class.getResource method is always treated as being relative to each entry in the classpath.

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

As your screenshot shows, the res directory is such a classpath entry. So the Class.getResource method treats the path you provide as relative to that entry. Meaning, relative to the res directory.

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

So, the method combines your string argument with that directory, which results in res/res/img/smile.png. Since no file (resource) exists at that location, it returns null.

这篇关于为什么class.getResource()保持返回null,虽然在指定的路径有一个资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆