Nirav
Nirav

Reputation: 5760

Fetch file from specific directory where jar file is placed

I want to fetch a text file from the directory where my jar file is placed.

Assuming my desktop application 'foo.jar' file is placed in d:\ in an installation of Windows. There is also a test.txt file in the same directory which I want to read when 'foo.jar' application is running. How can fetch that particular path in my 'foo.jar' application? In short I want to fetch the path of my 'foo.jar' file where it is placed.

Upvotes: 0

Views: 645

Answers (3)

Nirav
Nirav

Reputation: 5760

I found the shortest answer of my own question.
String path = System.getProperty("user.dir");

Upvotes: 0

Vineet Reynolds
Vineet Reynolds

Reputation: 76719

Most JARs are loaded using a URLClassLoader that remembers the codesource from where the JAR has been loaded. You may use this knowledge to obtain the location of the directory from where the JAR has been loaded by the JVM. You can also use the ProtectionDomain class to get the CodeSource (as shown in the other answer; admittedly, that might be better).

The location returned is often of the file: protocol type, so you'll have to remove this protocol identifier to get the actual location. Following is a short snippet that performs this activity; you might want to build in more error checking and edge case detection, if you need to use it in production:

public String getCodeSourceLocation() {
        ClassLoader contextClassLoader = CurrentJARContext.class.getClassLoader();
        if(contextClassLoader instanceof URLClassLoader)
        {
            URLClassLoader classLoader = (URLClassLoader)contextClassLoader;
            URL[] urls = classLoader.getURLs();
            String externalForm = urls[0].toExternalForm();
            externalForm = externalForm.replaceAll("file:\\/", "");
            externalForm = externalForm.replaceAll("\\/", "\\" + File.separator);
            return externalForm;
        }
        return null;
    }

Upvotes: 1

barti_ddu
barti_ddu

Reputation: 10309

Note, that actual code does depend on actual class location within your package, but in general it could look like:

URL root = package.Main.class.getProtectionDomain().getCodeSource().getLocation();
String path = (new File(root.toURI())).getParentFile().getPath();
...
// handle file.txt in path

Upvotes: 3

Related Questions