如何配置 sbt 在运行应用程序时加载资源? [英] How to configure sbt to load resources when running application?

查看:40
本文介绍了如何配置 sbt 在运行应用程序时加载资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码(Java)从 jar 中读取图像:

My code (Java) reads an image from jar:

Main.class.getResourceAsStream("/res/logo.png")

一切正常(如果我在将应用程序打包成罐子后启动它).但是当我使用 sbt 的 run 任务运行它时,它返回我 null 而不是需要的流.

Everything runs fine (if I start the app after packaging it into a jar). But when I run it using sbt's run task, it returns me null instead of needed stream.

从 sbt console 运行它也会给出 null:

Running this from sbt console also gives null:

getClass.getResourceAsStream("/res/logo.png")

有没有办法告诉 sbt 将我的资源放在类路径上?

Is there a way to tell sbt to put my resources on classpath?

我将资源目录设置为与源目录相同:

I set the resources dir to be same as source dir:

build.sbt:
resourceDirectory <<= baseDirectory { _ / "src" }

当我加载 sbt 的 `console' 并运行以下命令时:

When I loaded sbt's `console' and ran the following:

classOf[Main].getProtectionDomain().getCodeSource()

我得到了我的类的位置,但它既不包含 res 文件夹,也不包含我的任何资源文件.

I got the location of my classes, but it does not contain neither res folder nor any of my resource files.

似乎 sbt 只将资源复制到生成的 jar 中,而不会将它们复制到类目录中.我应该修改编译任务以将这些资源文件移动到类目录吗?

Seems that sbt copies resources only to the resulting jar, and does not copy them to classes dir. Should I modify compile task to move these resources files to classes dir?

编辑 2:

是的,当我手动将资源文件复制到 classes 目录时,我可以轻松地从控制台访问它.那么,我应该如何自动化这个过程?

Yes, when I manually copy the resource file to classes dir, I can easily access it from console. So, how should I automate this process?

编辑 3:

似乎 sbt 只是无法看到我的资源文件夹 - 实际上它并没有将文件添加到生成的 jar 文件中!

It seems that sbt is just unable to see my resource folder - it does not add files to resulting jar file, actually!

解决方案:

resourceDirectory in Compile <<= baseDirectory { _ / "src" }

推荐答案

我现在不能给你一个完整的解决方案,但有一个名为 resourceDirectories 的设置,你可以将 res 文件夹添加到其中.

I can't give you a full solution right now, but there is a setting called resourceDirectories to which you could add the res folder.

对我来说,如果资源位于标准资源文件夹中,它也不起作用.请以这种方式尝试:

For me it didn't work also if the resource was in the standard resource folder. Please try it that way:

Main.class.getClassLoader().getResourceAsStream("icon.png")

这是完整的构建脚本 (build.scala),如果您的资源位于 src/main/java 中,则该脚本有效:

This is the full build script (build.scala) which works if your resource is in src/main/java:

import sbt._
import Keys._

object TestBuild extends Build {

  lazy val buildSettings = Seq(
    organization := "com.test",
    version := "1.0-SNAPSHOT",
    scalaVersion := "2.9.1"
  )

  lazy val test  = Project(
    id = "test",
    base = file("test"),
    settings = Defaults.defaultSettings ++ Seq(resourceDirectory in Compile <<= javaSource in Compile)
  )
}

这篇关于如何配置 sbt 在运行应用程序时加载资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆