Where do I put my resources in Scala?

跟風遠走 提交于 2019-12-23 15:55:18

问题


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)

Where do I put the actual "AdoptionForm.fxml" content in this case? Unfortunately I am neither familiar with using resources in Java.

I use SBT as the building system and Idea as an IDE.

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


回答1:


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



来源:https://stackoverflow.com/questions/23361212/where-do-i-put-my-resources-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!