JavaXT

How to Get the Physical Location of a JAR File

In this tutorial, I will demonstrate how to find the jar file associated with a given class. In the past, I've used this information to debug class loaders, identify the version number of a given library, run apps found relative to a jar file, store configuration information, etc.

Here's a simple command line app used to return the physical location of the jar file. Note the 2 getJarFile() methods. One is used to find the physical location given a "Class", while the other will return a location using an instance of a class.


public class Test {

    public static void main(String[] args) throws Exception {
        System.out.println(getJarFile(Test.class));
    }
    
    
    public static java.io.File getJarFile(Object obj) throws Exception {
        return getJarFile(obj.getClass());
    }
    
    public static java.io.File getJarFile(Class _class) throws Exception {
        String path = _class.getPackage().getName().replace(".","/");
        String url = _class.getClassLoader().getResource(path).toString();
        url = url.replace(" ","%20");
        java.net.URI uri = new java.net.URI(url);
        if (uri.getPath()==null){
            path = uri.toString();
            if (path.startsWith("jar:file:")){

              //Update Path and Define Zipped File
                path = path.substring(path.indexOf("file:/"));
                path = path.substring(0,path.toLowerCase().indexOf(".jar")+4);

                if (path.startsWith("file://")){ //UNC Path
                    path = "C:/" + path.substring(path.indexOf("file:/")+7);
                    path = "/" + new java.net.URI(path).getPath();
                }
                else{
                    path = new java.net.URI(path).getPath();
                }
                return new java.io.File(path);                    
            }
        }
        else{
            return new java.io.File(uri);
        }
        return null;
    }
 }

Once you have the location of the jar file, you can parse it using the techniques described here:

Note that these JAR utilities/functions and more are available in the javaxt.io.Jar class.