我正在尝试查找 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/