[英]Listing xml files in a jar file
我有一個3rd party 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();
Jar是一個Zip文件,因此可以通過以下方式列出Jar中的文件:
ZipFile zipFile = new ZipFile("your.jar");
Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements()) {
System.out.println(zipEntries.nextElement().getName());
}
ZipEntry.getName()包含入口路徑(盡管沒有記錄),因此您可以使用String.startsWith(“ your / path”)之類的東西來檢測所需的入口路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.