3

I have a class in my Java application, which reads a resource folder which is located in src/main/resources. So, in that class, I am specifying the resource folder as:

public static final String RES_LOCATION = "./src/main/resources";

The program runs fine. But when I make a jar and use that as a dependency in another project, that above class fails as it cannot find the resource folder.

Any solution?

awesomemypro
  • 440
  • 3
  • 20

3 Answers3

3

You need to read particular file from that directory as a classpath resource instead of java.io.File

getClass().getResourceAsStream("relative/class/path/to/resource");
jmj
  • 225,392
  • 41
  • 383
  • 426
  • If I want to load files with particular extensions, what do you suggest? – awesomemypro Aug 28 '19 at 06:28
  • use the same technique but put the full file path in classpath and related to the cp. so replace `resource` in this example with `1.txt` for example – jmj Aug 28 '19 at 15:50
0

You are specifying the wrong resource path, you need to load the resource like resources 'public static final String RES_LOCATION = "resources"' as src/main will not be present.

Dinesh
  • 868
  • 1
  • 6
  • 17
  • Problem is, I was getting the name of the resource folder (src/main/resource) and listing all the files in that folder based on a particular extension. How can I achieve that in the jar? – awesomemypro Aug 28 '19 at 06:26
0

./src/main/resources is related to the structure of your project and is not the same when you package your code to .jar file. Both structures are very different and it can affect the way you access your file.

The best practice to access a file in a resource can be found on this page : https://www.mkyong.com/java/java-read-a-file-from-resources-folder/

Harry Coder
  • 597
  • 1
  • 9
  • 20