【发布时间】:2020-01-13 16:14:55
【问题描述】:
我做了一些搜索,在How do I get the last modification time of a Java resource?找到了一个类似的问题和答案
所以我稍微修改了代码,现在我的代码如下所示:
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.io.File;
import java.net.URL;
import java.nio.file.attribute.FileTime;
import java.text.DateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
public class GetBuildTime {
private static String getJarName() {
Class<?> currentClass = getCurrentClass();
return new File(currentClass.getProtectionDomain()
.getCodeSource() // Error at line 24
.getLocation()
.getPath())
.getName();
}
private static Class<?> getCurrentClass() {
return new Object() { }.getClass().getEnclosingClass();
}
private static boolean runningFromJAR() {
String jarName = getJarName();
return jarName.endsWith(".jar");
}
@RequiresApi(api = Build.VERSION_CODES.O)
public static String getLastModifiedDate() {
Date date=null;
try {
if (runningFromJAR()) {
String jarFilePath = getJarName();
try (JarFile jarFile = new JarFile(jarFilePath)) {
long lastModifiedDate = 0;
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
String element = entries.nextElement().toString();
ZipEntry entry = jarFile.getEntry(element);
FileTime fileTime = entry.getLastModifiedTime();
long time = fileTime.toMillis();
if (time > lastModifiedDate) lastModifiedDate = time;
}
date = new Date(lastModifiedDate);
}
} else {
Class<?> currentClass = getCurrentClass();
URL resource = currentClass.getResource(currentClass.getSimpleName() + ".class");
switch (resource.getProtocol()) {
case "file" : date = new Date(new File(resource.toURI()).lastModified()); break;
default : throw new IllegalStateException("No matching protocol found!");
}
}
} catch (Exception e) { e.printStackTrace(); }
if (date != null) {
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
return dateFormat.format(date);
} else return "";
}
}
但是当我在 Android Studio 中运行这个程序时,我得到了以下错误:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.security.CodeSource java.security.ProtectionDomain.getCodeSource()” 在 com.gate.gate_android.GetBuildTime.getJarName(GetBuildTime.java:24)
这样做的正确方法是什么?
【问题讨论】: