0

I have a propeties file with a path to a file inside my jar

logo.cgp=images/cgp-logo.jpg

This file already exists:

enter image description here

I want to load this file within my project so I do this:

String property = p.getProperty("logo.cgp"); //This returns "images/cgp-logo.jpg"
File file = new File(getClass().getClassLoader().getResource(property).getFile());

But then when I do file.exists() I get false. When I check file.getAbsolutePath() it leads to C:\\images\\cgp-logo.jpg

What am I doing wrong?

Averroes
  • 4,168
  • 6
  • 50
  • 63

2 Answers2

2

Well a file inside a jar is simply not a regular file. It is a resource that can be loaded by a ClassLoader and read as a stream but not a file.

According to the Javadocs, getClass().getClassLoader().getResource(property) returns an URL and getFile() on an URL says :

Gets the file name of this URL. The returned file portion will be the same as getPath(), plus the concatenation of the value of getQuery(), if any. If there is no query portion, this method and getPath() will return identical results.

So for a jar resource it is the same as getPath() that returns :

the path part of this URL, or an empty string if one does not exist

So here you get back /images/cgp-logo.jpg relative to the classpath that does not correspond to a real file on your file system. That also explains the return value of file.getAbsolutePath()

The correct way to get access to a resource is:

InputStream istream =  getClass().getClassLoader().getResourceAsStream(property)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

You can use the JarFile class like this:

JarFile jar = new JarFile("foo.jar");
String file = "file.txt";
JarEntry entry = jar.getEntry(file);
InputStream input = jar.getInputStream(entry);
OutputStream output = new FileOutputStream(file);
try {
    byte[] buffer = new byte[input.available()];
    for (int i = 0; i != -1; i = input.read(buffer)) {
        output.write(buffer, 0, i);
    }
} finally {
    jar.close();
    input.close();
    output.close();
}
adranale
  • 2,835
  • 1
  • 21
  • 39