我有一个第 3 方 jar,其中包含许多我想要处理的 xml 文件。我不知道名字或号码 xml 文件,但我确实知道它们打包在 jar 中的文件夹。
URL url = this.class.getResource("/com/arantech/touchpoint/index");
System.out.println(url.toString());
这似乎返回一个有效的文件(文件夹)路径
jar:file:/home/.m2/repository/com/abc/tp-common/5.2.0/tp-common-5.2.0.jar!/com/abc/tp/index
但是当我尝试列出文件夹中的文件时,我总是收到 NullPointerException
File dir = new File(url.toString());
System.out.println(dir.exists());
System.out.println(dir.listFiles().length);
有什么指导吗?
最佳答案
这样你就可以遍历主文件夹:
URL url = this.class.getResource("/com/arantech/touchpoint/index");
JarFile jar;
System.out.println("Loading JAR from: " + url.toString());
JarURLConnection URLcon = (JarURLConnection)(url.openConnection());
jar = URLcon.getJarFile();
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements())
{
JarEntry entry = (JarEntry) entries.nextElement();
if (entry.isDirectory() || !entry.getName().toLowerCase().endsWith(".xml"))
continue;
InputStream inputStream = null;
try
{
inputStream = jar.getInputStream(entry);
if (inputStream != null)
{
// TODO: Load XML from inputStream
}
}
catch (Exception ex)
{
throw new IllegalArgumentException("Cannot load JAR: " + url);
}
finally
{
if (inputStream != null)
inputStream.close();
}
}
jar.close();
关于java - 列出 jar 文件中的 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9741406/