【问题标题】:How to get the file location of a file in the classpath如何在类路径中获取文件的文件位置
【发布时间】:2014-05-21 01:43:27
【问题描述】:

我有以下场景,我有一些通用文本文件(配置文件模板),许多项目需要将其作为构建的一部分包含在内

最简单的方法是将该文件放在某个项目的main/resources 文件夹中,并通过依赖项包含该项目。

但是我需要该文件不只是在类路径中,它需要在类路径之外的文件夹中,例如/配置

我知道我可以使用映射选项,并且我知道映射的右侧,但左侧是什么?

例如

libraryDependencies += //some project that has /main/resouces/foo.conf in it   

mappings in Universal += classpathToFile("main/resources/foo.conf)  -> "conf/foo-external.conf"

我应该用什么代替classpathToFile


编辑: 我想我可以遍历整个类路径,例如

mappings in Universal ++= {
  val cp: Seq[File] = (fullClasspath in Runtime).value.files
  cp.filter(_.name.endsWith(".conf")).map(f => f -> "bin/" + f.name)
}

但我不确定这是不是最好的方法...

【问题讨论】:

  • 如果文件在您进行映射的当前项目之外,它很可能是 jar 的一部分,不是吗?那样你就找不到路径了。
  • 这只是一个猜测,但您似乎正在使用本机打包程序,并且您需要一个 conf 目录,这正是 play 所做的。如果你使用 play,那么最好将代码放在 app 目录下,将配置文件放在 conf 目录下。玩dist任务会为你处理包装......
  • 感谢 Gilad,但我没有使用 play :)

标签: scala sbt


【解决方案1】:

mappingsTuple2[File,String]的序列,其中文件部分表示某个文件(任意文件),字符串部分是生成的zip文件中的路径,文件将被打包到该路径。

例如:

mappings in Universal += (file("build.sbt"),"foo/build.sbt")

这意味着您的根项目中的build.sbt 文件将被打包到名为 foo 的文件夹下生成的 zip 文件中。该文件可以是您想要的任何文件。

编辑:

另外,定义你所做的事情的更好方法是:

mappings in Universal <++= (fullClasspath in Runtime) map {
  cp => {
    cp.files.filter(_.name.endsWith(".conf")).map(f => f -> "bin/" + f.name)
  }
}

【讨论】:

  • 是的,我很清楚 :) 问题是我如何获得我知道在我的类路径中的原始文件。该文件必须有一个很好的方法。我想我需要尝试一下getClass().getResource(...),才意识到...
  • 是的...看看类似的案例:stackoverflow.com/questions/20635556/…
  • 我做了你在编辑中所做的事情,但它不起作用......因为文件已经打包为 JAR。但是您提供的链接中的其他答案似乎很有希望,谢谢!
  • 如果您将其打包为 jar,则应使用 mappings in packageBin(或您可能使用的任何其他打包程序,如 oneJar 或 assemply,...)而不是 mappings in Universal
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 2013-07-17
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多