java - jar 内的类的上次更新时间

标签 java file jar last-modified .class-file

我正在尝试查找 jar 内文件的 .class 创建时间。 但是当我尝试使用这段代码时,我得到的是 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;

  }

 }

关于java - jar 内的类的上次更新时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37800062/

相关文章:

java - 无法在 Java 中创建临时文件

java - 导出为JAR后如何使JAVA接口(interface)被其他类设为 "implements"?

java - Maven - 如何配置 Maven 以满足这些要求

java - 一起使用数据提供程序和 TextNG XML

java - 处理小文件mapreducehadoop

java - 如何使用注释 Autowiring RestTemplate

java - Android Java - 下拉微调器始终设置相同的文本,只想更改背景颜色

php - 使用 PHP 将多个文件路径保存到 mysql

c# - 如何从 EnumerateFiles 中删除目录?

java - 如何在 Windows 上使用 Java Hotspot JVM 禁用小型转储 (mdmp) 文件生成