Java 为 class.getResource() 定义根类路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19104545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:07:49  来源:igfitidea点击:

defining root classpath for class.getResource()

javaclasspathclassloadergetresource

提问by user1028741

I'm using java in Eclipse (windows), and I'm trying to use:

我在 Eclipse (windows) 中使用 java,我正在尝试使用:

myClass.getResource("/image.jpg"), 

While image.jpg exists in the root loacation "myProject/". It returns null.

而 image.jpg 存在于根位置“myProject/”中。它返回空值。

I checked many other threads but none of them resolved my issue.

我检查了许多其他线程,但没有一个解决了我的问题。

So I tried to evaluate this:

所以我试图评估这一点:

this.getClass().getResource("/").getPath();

and it returned "myProject/build/classes".

它返回了“myProject/build/classes”。

So I checked the project's configuration for this dir, and found the exact same dir under

所以我检查了这个目录的项目配置,并在下面找到了完全相同的目录

Java Build Path --> Source --> Default output folder

Java 构建路径 --> 源 --> 默认输出文件夹

My questions are:

我的问题是:

  1. why is the default dir of my resources is the output folder?

  2. As mentioned, I want to get a resource from another folder, but attempts to call "/../" aren't working... How can I then load other resources which are not nested in my classes dir? (I can change my output dir, but I think it will be very ugly...)

  1. 为什么我的资源的默认目录是输出文件夹?

  2. 如前所述,我想从另一个文件夹中获取资源,但尝试调用“/../”不起作用......然后我如何加载未嵌套在我的类目录中的其他资源?(我可以更改我的输出目录,但我认为它会非常难看...)

采纳答案by angel_navarro

You must put them in the root of "src/" folder ;-)

您必须将它们放在“src/”文件夹的根目录中;-)

SRC/ folder is compiled to BUILD/CLASSES/, so all you put in src/* goes to classes/*

src/ 文件夹被编译为 BUILD/CLASSES/,所以你在 src/* 中放入的所有内容都会转到 classes/*