SparkOn
SparkOn

Reputation: 8946

getResource() unable to read contents of a directory inside jar

I just came around this issue that the main class inside jar is unable to read the contents of a folder. The class contains

String path = "flowers/FL8-4_zpsd8919dcc.jpg";
    try {
        File file = new File(TestResources.class.getClassLoader()
                                .getResource(path).getPath());
        System.out.println(file.exists());
    } catch (Exception e) {
        e.printStackTrace();
    }

Here sysout returns false.

But when I try something like this it works

    String path = "flowers/FL8-4_zpsd8919dcc.jpg";
    FileOutputStream out = null;
    InputStream is = null;
    try {
        is = TestResources.class.getClassLoader().getResourceAsStream(path);
        byte bytes[] = new byte[is.available()];
        is.read(bytes);
        out = new FileOutputStream("abc.jpg");
        out.write(bytes);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

getResourceAsStream() is able to read the path of the folder inside jar but getResource() is unable to read it,

why is it so and what is the difference between the reading mechanism of these two methods for contents inside jar. The contents of the simple jar

enter image description here

Upvotes: 2

Views: 1310

Answers (2)

icza
icza

Reputation: 417452

Both getResource() and getResourceAsStream() are able to find resources in jar, they use the same mechanism to locate resources.

But when you construct a File from an URL which denotes an entry inside a jar, File.exists() will return false. File cannot be used to check if files inside a jar/zip exists.

You can only use File.exists which are on the local file system (or attached to the local file system).

Upvotes: 2

Patrick Collins
Patrick Collins

Reputation: 10574

You need to use an absolute path to get the behavior you're expecting, e.g. /flowers/FL8-4_zpsd8919dcc.jpg, as sp00m suggested.

Upvotes: 0

Related Questions