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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With