通过 sbt 打包的 one-jar 中的类路径资源 [英] Classpath resources inside one-jar packaged via sbt
问题描述
我有一个使用 SBT 构建的项目,它使用 one-jar 插件打包单个 jar.该项目在 src/main/resources/fixture 中包含一堆 json 文件,我曾经通过
I have a project that is build using SBT which packages a single jar using the one-jar plugin. That project contains a bunch of json files in src/main/resources/fixture which I used to access via
new java.io.File(App.getClass.getResource("/fixture").getFile
不幸的是,这不再起作用,因为没有返回资源.我认为 one-jar 使用了一种特殊的类加载机制?解决这个问题的最佳方法是什么?
Unfortunately this doesn't work any longer since no Resource is returned. I think one-jar uses a special classloading mechanism? Whats the best way to solve this?
推荐答案
one-jar 将您的资源打包到输出 jar 中的 main
目录下.在使用sbt的时候,我觉得最好自己配置资源的打包.通常,我会这样做:
one-jar packages your resources under the main
dir in the output jar. when using sbt, I find it best to configure the packaging of resources myself.
usually, I would do something like this:
unmanagedResources in Compile := Seq() //we don't want to add resources from "src/main/resources" to inner jar
mappings in oneJar += (file("src/main/resources/filename.json"),"path/to/resource/in/onejar")
所以你的资源 filename.json
将被打包到你想要的地方.当您在运行时需要资源时,只需使用:
so your resource filename.json
will be packaged where you want it in the one-jar jar.
when you want the resource at runtime, simply use:
Thread.currentThread.getContextClassLoader.getResourceAsStream("path/to/your/resource")
看看 这篇文章.它可能有助于如何打包 src/main/resources
...
have a look at this post. it may help with how to package all the resources under src/main/resources
...
这篇关于通过 sbt 打包的 one-jar 中的类路径资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!