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

Iva*_*van 3 resources scala

在使用Scala和JavaFX学习时,我在ProScalaFX示例中遇到了以下代码:

  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)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我在哪里放置实际的"AdoptionForm.fxml"内容?不幸的是,我不熟悉在Java中使用资源.

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

有一个相关的问题暗示了一种方法(将资源文件放在"src/main/resources"或"src/main/resources/packagename"中),但它也说它实际上不起作用(不用说我有试过).

blu*_*e10 5

src/main/resources is the correct location for placing resources in a default SBT configuration.

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.

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.

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 /.

Example: getClass.getResource("/AdoptionForm.fxml") loads the resource from src/main/resources/AdoptionForm.fxml