Issue
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?
Solution
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.
Answered By - Innovationchef
Answer Checked By - Marie Seifert (JavaFixing Admin)