简体   繁体   English

Scala getClass.getResource() 返回 null

[英]Scala getClass.getResource() returning null

I have this code:我有这个代码:

val url: URL = getClass.getResource("com/mysite/main/test.fxml")

and it always returns null (or Unit ).它总是返回null (或Unit )。 I have only two files in the project:我的项目中只有两个文件:

MyProj/src/com/mysite/main/Test.scala
MyProj/src/com/mysite/main/test.fxml

and when I run the Test.scala the url value is always null.当我运行Test.scalaurl值始终为空。

I just tried rebuild the project, I am using IntelliJ IDEA.我刚刚尝试重建项目,我正在使用 IntelliJ IDEA。 What am I doing wrong here?我在这里做错了什么?

You have three options:您有三个选择:

  • take advantage of relative path to your current package (where Test.class is):利用当前包的相对路径( Test.class所在的Test.class ):

     getClass.getResource("test.fxml")
  • you can use absolute path:您可以使用绝对路径:

     getClass.getResource("/com/mysite/main/test.fxml")
  • or load through the ClassLoader (note that it always start from root):或者通过ClassLoader (注意它总是从 root 开始):

     getClass.getClassLoader.getResource("com/mysite/main/test.fxml")

In IntelliJ IDEA, make sure you have added ;?*.fxml to the:在 IntelliJ IDEA 中,确保已将;?*.fxml添加到:

Settings ( Preferences on Mac) | Settings (Mac 上的Preferences )| Compiler | Compiler | Resource Patterns .资源模式

Possibly it's not being copied to the bin/ directory from the src/ directory?可能它没有从 src/ 目录复制到 bin/ 目录? This happens on recompilation, but if you drop it into the src/ directory after the program is already compiled, the IDE won't know.这发生在重新编译时,但如果在程序编译后将其放入 src/ 目录,IDE 将不知道。

Late answer but I just had this same problem.迟到的答案,但我刚刚遇到了同样的问题。 The root cause was an incorrect rootProject.name entry in my settings.gradle.根本原因是我的 settings.gradle 中的 rootProject.name 条目不正确。 Once I fixed that, cleaned, and rebuilt my resource were able to load using getClass().getResource().一旦我解决了这个问题,清理并重建了我的资源就可以使用 getClass().getResource() 加载。 Hopefully that helps somebody.希望这可以帮助某人。

If it does not work, you can try with ClassLoader :如果它不起作用,您可以尝试使用ClassLoader

ClassLoader.getSystemResource("filename").getPath

The filename should be in the same directory layer文件名应该在同一个目录层

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM