jar 中 class 的最后更新时间

Last updated time for a class inside a jar

我正在尝试查找 .class 文件在 jar 中的创建时间。 但是当我尝试使用这段代码时,我得到的是 Jar 创建时间而不是 .class 文件创建时间。

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();
    }

但是当我打开 jar 时,我可以看到。class创建时间与 jar 创建时间不同。

能否请您尝试以下解决方案:

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;

  }

 }