4

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

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?

reikje
  • 2,850
  • 2
  • 24
  • 44

3 Answers3

2

I think one-jar uses a special classloading mechanism?

Yes, this must be true since there is no standardized way to load classes that packaged into dependency jar that is in turn packaged into your application jar. This usually is implemented with additional classloader trickery.

Loading resources when using One-JAR is documented here.

Eugene Loy
  • 12,224
  • 8
  • 53
  • 79
  • Thanks for pointing me to the resource docs. I finally got it working. Of the 3 potential locations, my resources were in the main/main.jar. My intention was to get the directory (File) packaged into the main.jar using MainClass.getClass.getResource("/dirname") and to iterate it's children (Files). That didn't work out. I was however able to load the contents of each file in that directory by using MainClass.getClass.getResourceAsStream("/dirname/filename.json") – reikje Dec 17 '13 at 22:08
2

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

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

have a look at this post. it may help with how to package all the resources under src/main/resources...

Community
  • 1
  • 1
gilad hoch
  • 2,846
  • 2
  • 33
  • 57
0

I found that Spring's core PathMatchingResourcePatternResolver can do this. It's also can find files according to pattern.

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");
Yuri
  • 185
  • 1
  • 13