How to Get the Version Number of a JAR File

There are 2 common ways vendors use to version a jar file:

Parsing the Manifest

The preferred mechanism for storing version information is to use the Manifest file. There are two keywords commonly used to store version information in the manifest: "Implementation-Version" and "Bundle-Version". Here's a simple script you can use to find the version number in the Manifest:

    java.io.File file = new java.io.File("/drivers/h2/h2-1.3.162.jar");
    java.util.jar.JarFile jar = new java.util.jar.JarFile(file);
    java.util.jar.Manifest manifest = jar.getManifest();
    
    String versionNumber = "";
    java.util.jar.Attributes attributes = manifest.getMainAttributes();
    if (attributes!=null){
        java.util.Iterator it = attributes.keySet().iterator();
        while (it.hasNext()){
            java.util.jar.Attributes.Name key = (java.util.jar.Attributes.Name) it.next();
            String keyword = key.toString();
            if (keyword.equals("Implementation-Version") || keyword.equals("Bundle-Version")){
                versionNumber = (String) attributes.get(key);
                break;
            }
        }
    }
    jar.close();

    System.out.println("Version: " + versionNumber); //"Version: 1.3.162"

Parsing the File Name

If, for whatever reason, the version information is not found in the manifest, you can try to parse the jar file name. This is extremely error prone but sometimes its your only option. Here's a simple script to extract the version number from the file name.

    java.io.File file = new java.io.File("/drivers/h2/h2-1.3.162.jar");
    String versionNumber = "";
    String fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
    if (fileName.contains(".")){
        String majorVersion = fileName.substring(0, fileName.indexOf("."));
        String minorVersion = fileName.substring(fileName.indexOf("."));
        int delimiter = majorVersion.lastIndexOf("-");
        if (majorVersion.indexOf("_")>delimiter) delimiter = majorVersion.indexOf("_");
        majorVersion = majorVersion.substring(delimiter+1, fileName.indexOf("."));
        versionNumber = majorVersion + minorVersion;
    }
    System.out.println("Version: " + versionNumber); //"Version: 1.3.162"

javaxt.io.Jar

Note that the javaxt.io.Jar class can be used to return the version of a jar file with one simple call. The getVersion() method combines both techniques described here into one method. Example:

System.out.println("Version: " + new javaxt.io.Jar(file).getVersion());

Related Articles