0

I have a 3rd party jar that contains a number of xml files that i'd like to process. I don't know the name or number of xml files but i do know the folder where they are packaged within the jar.

URL url = this.class.getResource("/com/arantech/touchpoint/index");
System.out.println(url.toString());

this seems to return a valid file (folder) path

jar:file:/home/.m2/repository/com/abc/tp-common/5.2.0/tp-common-5.2.0.jar!/com/abc/tp/index

but when i attempt to list the files in the folder i always get a NullPointerException

File dir = new File(url.toString());
System.out.println(dir.exists());
System.out.println(dir.listFiles().length);

Any guidance?

skaffman
  • 398,947
  • 96
  • 818
  • 769
emeraldjava
  • 10,894
  • 26
  • 97
  • 170
  • That *isn't* a valid folder path, it's a synthetic URL that points at a resource inside a JAR file. You can't treat the contents of JAR files as though they were themselves files. – skaffman Mar 16 '12 at 16:59
  • possible duplicate of [How do I list the files inside a JAR file?](http://stackoverflow.com/questions/1429172/how-do-i-list-the-files-inside-a-jar-file) – skaffman Mar 16 '12 at 17:00

2 Answers2

1

With this you could traverse the main folder:

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();
WindRider
  • 11,958
  • 6
  • 50
  • 57
0

Jar is a Zip file, so listing files within a Jar could be done with:

ZipFile zipFile = new ZipFile("your.jar");
Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements()) {
    System.out.println(zipEntries.nextElement().getName());
}

ZipEntry.getName() contains entry path (although it's not documented) so you can detect the ones that you need by using something like String.startsWith("your/path").

Oleg Mikheev
  • 17,186
  • 14
  • 73
  • 95