Question

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

  • to add the folder to the resource dir
  • to add the folder to the root dir (same layer like src)
  • add the Config folder to the resource dir

Solution:

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

Was it helpful?

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");

OTHER TIPS

This should help you reading xml file inside a jar-package

"You can't get a File object (since it's no longer a file once it's in the .jar), but you should be able to get it as a stream via getResourceAsStream(path)"

If everything is packed, then you should get resources with the getResource the same way you get the images but may be different path.

URL url = getClass().getResource("/defaultConfig/config.xml");

Then you can read directly from this url. See Reading Directly from a URL.

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

String inputLine;
while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);
in.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top