我应该把我的资源放在 Scala 的什么地方? [英] Where do I put my resources in Scala?
问题描述
在学习将 Scala 与 JavaFX 结合使用时,我在 ProScalaFX 示例中遇到了以下代码:>
While studying using Scala with JavaFX I have met the following code in a ProScalaFX example:
val resource = getClass.getResource("AdoptionForm.fxml")
if (resource == null) {
throw new IOException("Cannot load resource: AdoptionForm.fxml")
}
...
val root: jfxs.Parent = jfxf.FXMLLoader.load(resource)
在这种情况下,我应该将实际的AdoptionForm.fxml"内容放在哪里?不幸的是,我不熟悉在 Java 中使用资源.
Where do I put the actual "AdoptionForm.fxml" content in this case? Unfortunately I am neither familiar with using resources in Java.
我使用 SBT 作为构建系统,使用 Idea 作为 IDE.
I use SBT as the building system and Idea as an IDE.
有一个相关问题,它提出了一种方法(将资源文件放在src/main/resources"或src/main/resources/packagename"中),但它也说它实际上不起作用(不用说我已经尝试过).
There is a related question which suggests a way (putting the resource files in "src/main/resources" or "src/main/resources/packagename"), but it also says it doesn't work actually (needless to say I have tried).
推荐答案
src/main/resources
是在默认 SBT 配置中放置资源的正确位置.
src/main/resources
is the correct location for placing resources in a default SBT configuration.
但是,必须注意 getClass.getResource
和 ClassLoader 之间的区别.获取资源
.使用 getClass.getResource("AdoptionForm.fxml")
要求文件位于与类的包对应的路径中.
However, one has to be aware of the difference between getClass.getResource
and ClassLoader.getResource
. Using getClass.getResource("AdoptionForm.fxml")
requires the file to be located in a path which corresponds to the package of the class.
例如:如果类位于com.domain.utils
,那么资源必须位于src/main/resources/com/domain/utils/AdoptionForm.fxml代码>.
For instance: If the class is located in com.domain.utils
then the resource must be located at src/main/resources/com/domain/utils/AdoptionForm.fxml
.
为了从包相对位置切换到绝对位置,可以使用 ClassLoader.getResource
或只是在资源字符串前面加上 /
.
In order to switch from package-relative locations to absolute locations one can either use ClassLoader.getResource
or just prepend the resource string with a /
.
示例:getClass.getResource("/AdoptionForm.fxml")
从 src/main/resources/AdoptionForm.fxml
这篇关于我应该把我的资源放在 Scala 的什么地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!