简体   繁体   中英

Last updated time for a class inside a jar

I'm trying to find the .class creation time for a file inside a jar. But When I try to use this piece of code, I'm getting the Jar creation time instead of the .class file creation time.

URL url = TestMain.class.getResource("/com/oracle/determinations/types/CommonBuildTime.class");
    url.getPath();
    try {
        System.out.println(" Time modified :: "+ new Date(url.openConnection().getLastModified()));
    } catch (IOException e) {
        e.printStackTrace();
    }

But when I open the jar I can see the .class creation time is different from that of the jar creation time.

Could you please try following solution:

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Test {

public static void main(String[] args) throws IOException {
  String classFilePath = "/com/mysql/jdbc/AuthenticationPlugin.class";
  String jarFilePath = "D:/jars/mysql-connector-java-5.1.34.jar";     
  Test test=new Test();
  Date date = test.getLastUpdatedTime(jarFilePath, classFilePath);
  System.out.println("getLastModificationDate returned: " + date);
 }

/**
 * Returns last update time of a class file inside a jar file 
 * @param jarFilePath - path of jar file
 * @param classFilePath - path of class file inside the jar file with leading slash
 * @return 
 */
public Date getLastUpdatedTime(String jarFilePath, String classFilePath) {
JarFile jar = null;
try {
    jar = new JarFile(jarFilePath);
    Enumeration<JarEntry> enumEntries = jar.entries();
    while (enumEntries.hasMoreElements()) {
        JarEntry file = (JarEntry) enumEntries.nextElement();
        if (file.getName().equals(classFilePath.substring(1))) {
            long time=file.getTime();
            return time==-1?null: new Date(time);
        }

    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (jar != null) {
        try {
            jar.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 }
 return null;

  }

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM