Skip to content
Advertisement

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.

Advertisement

Answer

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;
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement