我在哪里将资源放在Scala中?

时间:2014-04-29 09:49:57

标签: scala resources

在使用Scala和JavaFX学习时,我在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中使用资源。

我使用SBT作为构建系统,将Idea作为IDE使用。

有一个related question暗示了一种方式(将资源文件放在“src / main / resources”或“src / main / resources / packagename”中),但它也说它实际上不起作用(不用说我已经尝试过了。)

1 个答案:

答案 0 :(得分:5)

src/main/resources是将资源置于默认SBT配置中的正确位置。

但是,必须要注意difference between getClass.getResource and ClassLoader.getResource。使用getClass.getResource("AdoptionForm.fxml")要求文件位于与类的包对应的路径中。

例如:如果课程位于com.domain.utils,则资源必须位于src/main/resources/com/domain/utils/AdoptionForm.fxml

为了从包相对位置切换到绝对位置,可以使用ClassLoader.getResource或仅使用/添加资源字符串。

示例:getClass.getResource("/AdoptionForm.fxml")src/main/resources/AdoptionForm.fxml

加载资源