Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JAR compilation time

I am trying to get the compilation time of the runnable JAR file I am exporting from Eclipse. One way to do this would probably be to get the modification time of the META-INF/MANIFEST.MF file. Unfortunately I can't seem to find a way to get this information (I know how to read the manifest itself using getResourceAsStream("/META-INF/MANIFEST.MF"), but I can't seem to be able to read its modification time).

Has anybody some insight on how to do it?

like image 527
CAFxX Avatar asked Mar 29 '12 14:03

CAFxX


People also ask

Is jar file already compiled?

A . jar file contains compiled code (*. class files) and other data/resources related to that code. It enables you to bundle multiple files into a single archive file.


2 Answers

If you have access to the jar file itself, you should be able to read the jar file using java.util.jar package, then get ZipEntry for the Manifest file and use getTime() on it to get its last update time.

JarFile jf = new JarFile("myfile.jar");
ZipEntry manifest = jf.getEntry("META-INF/MANIFEST.MF");
long manifestTime = manifest.getTime();  //in standard millis

If you need to deal with the specific class, then you may find this code also useful;

String rn = this.getClass().getName().replace('.', '/') + ".class";
String path = getClass().getClassLoader().getResource(rn).getPath();
String jarFile = path.substring(0, path.indexOf("!"));

Then jarFile will contain the path name of your jar. Note that if the class is not loaded from the jar file, then the third line will fail, as path.indexOf will return -1.

like image 198
Aleks G Avatar answered Sep 28 '22 22:09

Aleks G


In the end, based on Aleks G's answer and others found elsewhere, I came up with a more robust solution (that e.g. works also on network shares):

public static Long getTime(Class<?> cl) {
    try {
        String rn = cl.getName().replace('.', '/') + ".class";
        JarURLConnection j = (JarURLConnection) cl.getClassLoader().getResource(rn).openConnection();
        return j.getJarFile().getEntry("META-INF/MANIFEST.MF").getTime();
    } catch (Exception e) {
        return null;
    }
}

I was hoping for a better way to go from the Class object to the resource name but I guess this will have to do.

like image 30
CAFxX Avatar answered Sep 28 '22 23:09

CAFxX