javaeclipseexecutable-jarfile-import

Resources with Eclipse and runnable Jar


I've the following file structure:

+-src
  +-- code
+-resources
  +-- img
    +- logo.png
  +-- defaultConfig
    +- config.xml

When i run the code in Eclipse it worked, since exporting to runnable jar, it haven't found the defaultConfig files

I'm Accessing a Logo this way and it works

URL url = getClass().getResource("/img/logo.png");
setIconImage(new ImageIcon(url).getImage());

Accessing the config.xml doesn't work with different set ups.

this was given:

File config = new File("resources/defaultConfig/config.xml");

after a lot of searching i tried this one:

//example
String path = "resources\\defaultConfig\\config.xml");
File config = new File(createURIFromString(path));

I've tried it with ./ & .\ without .

private URI createURIFromString(String path) {
    URI id = null;
    try {
        id =    getClass().getResource(path).toURI();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return id;
}

Result is a null Pointer.

I've tried

Solution:

previously the file weren't in the jar, so till using the getResorce method, it works.


Solution

  • Why are you creating a File object? Your data is embedded within the jar file; there's no File object you can construct that refers to it (unless you've got a custom file system somewhere).

    You need to rip out anything which requires the configuration to be read from a file, and instead make it take any InputStream. You can then use

    InputStream stream = Foo.class.getResourceAsStream("/defaultConfig/config.xml");