简体   繁体   中英

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()) .

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.

资源文件位置

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) throws IOException {
        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");
        }
    }
}

Inside jar, resource file will be as follows.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM