Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

java - Get path of a file in resourcer even when its in a jar

I have a Json file in resources and I am using this code to use the information that it have:

JsonClass myWantedInfo;
Gson gson = new GsonBuilder().serializeNulls().create();
URL res = getClass().getClassLoader().getResource("file.json");
Writer writer = Files.newBufferedWriter(Paths.get(res.toURI()));
gson.toJson(myWantedInfo, writer);
writer.close();

When i use my IDE (Eclipse - Spring Tool Suite 4), this code works. But when i build a JAR of my proyect its throw me an error (FileNotFoundException). I have search a little and I found that the reason is that in my code the source is in src/main/resources but in the jar is at the root directory. But I don't find how can I resolve this problem.

To build the jar, I go to the path where my pom is and, using cmd, I use: mvn clean install.

Sorry for my bad english.

question from:https://stackoverflow.com/questions/65901183/get-path-of-a-file-in-resourcer-even-when-its-in-a-jar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had a similar error with reading properties file. After a bit of research I added this piece of code to pom:

<build>
        <resources>
            <resource>
                <directory>src/main/resources/</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
</build>

And this is how I read from the file:

/**
 * loads default config from internal source
 *
 * @return true/false upon success/failure of loading config
 */
private static boolean loadDefault() {

    if (null != properties) return false;

    try (InputStream resourceStream = Config.class.getClassLoader().getResourceAsStream("config.properties")) {
        properties = new Properties();
        properties.load(resourceStream);
        return true;

    } catch (NullPointerException | IOException exception) {

        String detail = ExceptionHandler.format(exception, "Could not load default config");
        log.error(detail);

        properties = null;
        return false;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...