我正在尝试读取可从项目根目录访问的文件夹中的 jar 内容,该 jar 已正确找到,但是,我的代码仅打印 META-INF
文件,这是我到目前为止尝试过的:
public static void provideClassList(String jarName) {
List<String> classNames = new ArrayList<String>();
ZipInputStream zip;
try {
zip = new ZipInputStream(new FileInputStream(StaticValues.JARS_PATH.concat(jarName)));
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
System.out.println(entry);//PRINTS META-INF/
if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
String className = entry.getName().replace('/', '.');
classNames.add(className.substring(0, className.length() - ".class".length()));
}
zip.close();
}
// explore content (THIS IS ACTUALLY EMPTY)
for (String className : classNames) {
try {
Class<?> clazz = Class.forName(className);
System.out.println(clazz.getCanonicalName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException ex) {
}
}
我看不到任何权限问题,而且我已经从控制台手动打开了 jar 文件,我期望找到的内容都在那里。 这些是我从 eclipse 看到的属性:
最佳答案
您正在 for 循环内调用 zip.close();
,这可能是您只获得 jar 中第一个条目的原因。将其移到 for 循环之外,或者更好的是,使用 try-with-resources 语句。
try (FileInputStream fis = new FileInputStream(StaticValues.JARS_PATH.concat(jarName);
ZipInputStream zip = new ZipInputStream(fis)) {
// code for iterating goes here
}
关于java - 探索 jar 内容时仅可用元/inf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33297477/