【发布时间】:2019-12-04 06:09:54
【问题描述】:
我正在尝试在 web 应用程序中编写代码,我的类路径中有一个 JAR 文件。目的是检查目录是否存在于 JAR 中。如果是,我需要将 JAR 目录中文件的所有内容保存在 HashMap<String, String> 中。 Key 是文件名,value 是每个文件的内容。
File directory = new File(getClass().getClassLoader().getResource(directoryPath).getPath());
System.out.println("PATH IS: " + directory.getPath());
// Check if dirPth exists and is a valid directory
if (!directory.isDirectory()) {
throw new AccessException("Directory \"" + directoryPath + "\" not valid");
}
// Obtain a list of all files under the dirPath
File [] fileList = directory.listFiles();
for (File file : fileList) {
if (file.isFile()) {
// Read the file
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
// Store the file data in the hash
entry.put(file.getName(), sb.toString);
}
}
direcotry.getPath() 的输出是:
文件:\H:\apache-tomcat-9.0.27\lib\myConfigurationFiles.jar!\META-INF\Maintenance\xmlFiles\secondary
这是我正在寻找的正确文件夹。
这里的 Map 对象是“入口”。
现在我不确定为什么 direcotry.isDirectory() 返回 false。它不应该返回 true 吗?
现在因为它没有跨越第一个异常。我不知道在那之后它会如何表现。任何帮助将不胜感激。
【问题讨论】:
-
该 URI 实际上向您表明它是一个 inside JAR 文件,这意味着您不能以
File的形式打开它。您不能对 JAR 中的资源使用File和文件操作,只能使用流操作。 jar 中没有“真正的”目录,因为它不是文件系统,它只是一个存档。 -
这段代码有几个问题。首先,jar 文件不是目录,因此您不能像这样列出 jar 文件的内容。其次,如果在不同的上下文中运行,这段代码可能会出现问题,webapps 类加载器是复杂的野兽。
-
我也在干预
JarFile。但我所能做的就是遍历文件夹/文件名,而不是获取文件夹内的文件或读取文件的内容。