Search code examples
javajarcompilationapplication.properties

How to Access Properties File Within Executable JAR


I have a properties file stored within /resources folder in my java Project. picture of resource folder

Here is my code:

String fileName = "config.properties";
            
try (InputStream input = Main.class.getClassLoader().getResourceAsStream(fileName)) {
     if (input == null) {
          System.out.println("Sorry, unable to find " + fileName);
          return properties;
     }
            
            
     properties = new Properties();
     properties.load(input);

when I run the code in my IDE it works as intended... but when I export the project as an "runnable Jar file" and run the application using: java -jar <nameOfJar>.jar

output of executable JAR

Here is the resource folder present in the JAR file: enter image description here

Can someone please explain to me why I can't read/load the properties file when it's converted to an executable JAR? Am I using the wrong file name?

EDIT pom.xml screenshot: pom.xml


Solution

  • Perhaps this method will help shed a little light:

    /**
     * Text files loaded with this method will work either within the IDE or your 
     * distributive JAR file.<br><br>
     * 
     * This method requires the Resource folder to be named "resources" which also 
     * contains a sub-folder named "textfiles". This resource folder is to be located 
     * directly within the Project "src" folder, for example:<pre>
     * 
     *      ProjectDirectoryName
     *          bin
     *          build 
     *          lib
     *          dist
     *          src
     *              resources
     *                  images
     *                      myImage_1.png
     *                      myImage_2.jpg
     *                      myImage_3.gif
     *                  textfiles
     *                      data_1.txt
     *                      data_2.txt
     *                      data_3.txt
     *          test</pre><br>
     * 
     * @param filePath (String) Based on the example folder structure above this 
     * would be (as an example):<pre>
     * 
     *    <b>  "/resources/textfiles/data_2.txt"  </b></pre>
     * 
     * @return ({@code List<String>}) A List of String containing the file's content.
     */
    public List<String> loadFileFromResources(String filePath) throws IOException {
        List<String> lines = new ArrayList<>();
        try (java.io.InputStream in = getClass().getResourceAsStream(filePath);
        java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(in))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
            reader.close();
        }
        return lines;
    }