2013-12-17 58 views
4

我有一个使用SBT构建的项目,它使用one-jar插件打包单个jar。该项目包含的src /主/资源/夹具一堆的JSON文件我用它通过通过sbt打包的one-jar中的类路径资源

new java.io.File(App.getClass.getResource("/fixture").getFile 

访问不幸的是,这并不工作下去,因为不返回任何资源。我认为one-jar使用特殊的类加载机制?什么是解决这个问题的最好方法?

回答

2

我觉得one-jar使用了一个特殊的类加载机制?

是的,因为有可以加载打包成依赖罐子后者又打包到您的应用程序罐子类没有标准化方式这必须是真实的。这通常是通过额外的类加载器欺骗来实现的。

使用One-JAR时加载资源是documented here

+0

感谢您指点我的资源文档。我终于搞定了。在三个潜在的位置中,我的资源位于main/main.jar中。我的目的是使用MainClass.getClass.getResource(“/ dirname”)获取打包到main.jar中的目录(File)并迭代它的子项(Files)。那没有成功。然而,我却可以通过使用MainClass.getClass.getResourceAsStream(“/ dirname/filename.json”) – reikje

+0

@ user1671319 cool来加载该目录中每个文件的内容。很高兴它有帮助。 –

2

one-jar将您的资源打包在main目录下的输出罐中。当使用sbt时,我发现最好自己配置资源的打包。 通常情况下,我会做这样的事情:

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将被打包,你想让它在一个罐子罐子。 当你想在运行时的资源,只需使用:

Thread.currentThread.getContextClassLoader.getResourceAsStream("path/to/your/resource") 

看看this post。它可能有助于如何将所有资源打包在src/main/resources ...

+0

+ 1这看起来正是我要找的,谢谢 –

0

我发现Spring的核心PathMatchingResourcePatternResolver可以做到这一点。它也可以根据模式找到文件。

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); 
resolver.getResources("classpath*:some/package/name/**/*.xml");