MemLeak
MemLeak

Reputation: 4640

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.

Upvotes: 0

Views: 3859

Answers (3)

Roman C
Roman C

Reputation: 1

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

Upvotes: 0

Dan Iliescu
Dan Iliescu

Reputation: 435

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500385

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

Upvotes: 3

Related Questions