gpt4 book ai didi

上次编译的 Java 打印时间

转载 作者:IT老高 更新时间:2023-10-28 20:32:18 27 4
gpt4 key购买 nike

我希望嵌入一段代码,该代码将打印出当前类最后一次编译的时间。这如何在 Java 中实现?

最佳答案

这个问题很久以前就有答案了。但万一有人经过这里有一个适合我的解决方案,类似于 Supah Fly 的建议,但支持 jar 和文件。

private long classBuildTimeMillis() throws URISyntaxException, IllegalStateException, IllegalArgumentException {
URL resource = getClass().getResource(getClass().getSimpleName() + ".class");
if (resource == null) {
throw new IllegalStateException("Failed to find class file for class: " +
getClass().getName());
}

if (resource.getProtocol().equals("file")) {

return new File(resource.toURI()).lastModified();

} else if (resource.getProtocol().equals("jar")) {

String path = resource.getPath();
return new File(path.substring(5, path.indexOf("!"))).lastModified();

} else {

throw new IllegalArgumentException("Unhandled url protocol: " +
resource.getProtocol() + " for class: " +
getClass().getName() + " resource: " + resource.toString());
}
}

但这不会处理 zip 文件或静态上下文,并且如果事情不顺利,它会抛出异常而不是返回 null。这个比较友好一点:

private static final Date buildDate = getClassBuildTime();

/**
* Handles files, jar entries, and deployed jar entries in a zip file (EAR).
* @return The date if it can be determined, or null if not.
*/
private static Date getClassBuildTime() {
Date d = null;
Class<?> currentClass = new Object() {}.getClass().getEnclosingClass();
URL resource = currentClass.getResource(currentClass.getSimpleName() + ".class");
if (resource != null) {
if (resource.getProtocol().equals("file")) {
try {
d = new Date(new File(resource.toURI()).lastModified());
} catch (URISyntaxException ignored) { }
} else if (resource.getProtocol().equals("jar")) {
String path = resource.getPath();
d = new Date( new File(path.substring(5, path.indexOf("!"))).lastModified() );
} else if (resource.getProtocol().equals("zip")) {
String path = resource.getPath();
File jarFileOnDisk = new File(path.substring(0, path.indexOf("!")));
//long jfodLastModifiedLong = jarFileOnDisk.lastModified ();
//Date jfodLasModifiedDate = new Date(jfodLastModifiedLong);
try(JarFile jf = new JarFile (jarFileOnDisk)) {
ZipEntry ze = jf.getEntry (path.substring(path.indexOf("!") + 2));//Skip the ! and the /
long zeTimeLong = ze.getTime ();
Date zeTimeDate = new Date(zeTimeLong);
d = zeTimeDate;
} catch (IOException|RuntimeException ignored) { }
}
}
return d;
}

关于上次编译的 Java 打印时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3336392/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com