skitou
skitou

Reputation: 3

Cannot get file from ressources folder

I want to get a file from the ressources folder, I tried many ways to do it but it has always failed.

Here's what I'm currently using to do it

File bundledConfigFile = new File(Objects.requireNonNull(Config.class.getClassLoader().getResource("config.json")).getPath());
        System.out.println(bundledConfigFile);
        try {
            parseConfig(rootConfigFile);
        } catch (IOException e) {
            logger.error("Can't access config : ", e);
            Runtime.getRuntime().exit(ExitCodes.ERROR.getValue() + ExitCodes.UNRECOVERABLE.getValue());
}

And it always tells me that error:


    [13:13:09.006] main  Config ERROR  Can't access config : 
    java.io.FileNotFoundException: config.json (Le fichier spécifié est introuvable)
        at java.base/java.io.FileInputStream.open0(Native Method)
        at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
        at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
        at java.base/java.io.FileReader.<init>(FileReader.java:75)
        at org.laconfrerie.discord.javabot.core.Config.parseConfig(Config.java:138)
        at org.laconfrerie.discord.javabot.core.Config.<init>(Config.java:41)
        at org.laconfrerie.discord.javabot.core.Config.getUnsafeProperty(Config.java:80)
        at org.laconfrerie.discord.javabot.core.Config.getProperty(Config.java:93)
        at org.laconfrerie.discord.javabot.core.Main.main(Main.java:43)

I don't understand why it cannot find it because the parseConfig(rootConfigFile) returns the good path, aka

D:\Documents\DEV\LaConf\Javabot\build\resources\main\config.json

Any solution to my issue ?

Upvotes: 0

Views: 71

Answers (1)

Stephen C
Stephen C

Reputation: 718836

When you put a file into a JAR file, it no longer has a pathname in the file system. That means it is impossible to create a File that refers to that copy of the resource.

Your alternatives are:

  • Open the resource using getResourceAsStream and read it that way.
  • Refer to the resource using its resource URL; i.e. the URL returned by getResource.
  • Copy the resource out of the JAR file into a temporary file and use the File for the temporary file.

Note that if the getResource call returns a "file:" URL that can be converted to a filesystem pathname, then you can do this:

  URL url = ... getResource(...);
  URI uri = url.toURI();
  File file = new File(uri);

If the preconditions for conversion of the URI to a file system pathname are not satisfied, the File constructor will throw an exception.

(That is what will happen for a resource in a JAR file.)

Also, note that a file: URL that denotes a non-existent file will be converted into a File that also denotes a non-existent file. You won't be able to open and read it.

Upvotes: 1

Related Questions