Search code examples
javaspring-bootmavenjar

How to get Path to resource folder in jar file


I have a Spring Boot 2.5.4 application using Java 11. Running in my IDE the following code is fine:

Path directory = Paths.get("src/main/resources");
log.info("PATH: " + directory.toAbsolutePath());

But if I build a jar file with Maven the directory does not exist. Which String can I use in Paths.get to have a proper Path instance pointing to resources folder in my Spring project?


Based on first comments I tried this:

var loader = ClassLoader.getSystemClassLoader();
// "templates" is directory in "src/main/resources"
var resDir = loader.getResource("templates");
Path directory = Path.of(resDir.toURI());

This is again working in my IDE, but in jar file I get a NullPointerException in Path.of(resDir.toURI()).


Solution

  • Use class that is in parellel to the resource and use its getResourceAsStream method. For an example for following structure you can use below code.

    resource file location

    package com.aptkode;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.charset.StandardCharsets;
    
    public class GetResourceInJar {
        public static void main(String[] args) {
        try(final InputStream stream = GetResourceInJar.class.getResourceAsStream("com/aptkode/resource.txt")) {
            if (stream != null) {
                final String text = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
                System.out.println(text);
            } else {
                System.err.println("failed to read text");
            }
        }
        catch (Exception e)
        {
            System.err.println(e.getMessage());
        }
    }
    }
    

    Inside jar, resource file will be as follows.

    resource file inside jar

    Running command java -jar .\target\get-resource-in-jar-1.0-SNAPSHOT.jar will print the content. Following is the maven jar plugin configuration.

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.2.0</version>
        <configuration>
            <archive>
                <manifest>
                    <mainClass>
                        com.aptkode.GetResourceInJar
                    </mainClass>
                </manifest>
            </archive>
        </configuration>
    </plugin>