0

How do you store a file inside a jar library?

Setup : Create a simple maven project with a class that loads something from the resources folder using the getResoruceAsStream() method and a test that runs it. The test will fail with the problem being it couldn't find that file, the same issue will appear later when we try to compile it as a lib and run that class.

The problem : Using the only method I know (and the only that you can find on the web) getResourceAsStream() will give you a null reference exception, because the file is missing. So how do I add the file to the jar and load it later?

luk2302
  • 55,258
  • 23
  • 97
  • 137
Luka K.
  • 55
  • 8
  • Does this answer your question? [Reading a resource file from within jar](https://stackoverflow.com/questions/20389255/reading-a-resource-file-from-within-jar) – luk2302 Feb 24 '21 at 19:34

1 Answers1

1

Keep the file in the src/main/resources directory and use the following method in the class where you need to load that file -

private InputStream readFileFromResourcePath(String filename) {
    return getClass().getClassLoader().getResourceAsStream(filename);
} 

Do not forget to close the stream after consuming it.

Innovationchef
  • 338
  • 2
  • 10
  • Ah, when porting i forgot that older java versions build with ant didnt have a concept of the resources folder – Luka K. Feb 25 '21 at 09:09