How to _directly_ get a list of files from a sub-d

2019-03-02 07:41发布

问题:

I'm looking for a way to directly get a list of all files within a specified sub-directory within a .jar.

This is similar: How do I list the files inside a JAR file?

But unfortunately the method listed above will iterate over all files in the entire .jar. When working with a .jar with many files in it - this seems impractical as is my case. There has to be a way to directly path to a sub directory within the .jar and iterate over its contents, without having to iterate over all contents of the jar and then filter the results to find those entries that you care about.

Here is roughly what I have:

public static ArrayList<String> loadInternalFileListing(MetaDataType type, MetaDataLocation location, String siteId)
{
  ArrayList<String> filenameList = new ArrayList<String>();
  URL url = getInternalFile(type, null, location, siteId);

  JarURLConnection juc = null;
  JarFile jarFile = null;

  try
  {
    juc = (JarURLConnection) url.openConnection();
    jarFile = juc.getJarFile();
    Enumeration<JarEntry> entries = jarFile.entries();

    for(JarEntry jarEntry = entries.nextElement(); entries.hasMoreElements(); jarEntry = entries.nextElement())
    {
       ...//logic here
    }
  }
  ... //catch, handle exceptions, finally block and other logic

  return filenameList;
}

The variable: url ->: jar:file:/C:/jboss-4.2.2.GA/server/username/tmp/deploy/tmp8421264930467110704SomeEar.ear-contents/SomeBusiness.jar!/subdir1/subdir2/subdir3/subdir4/

The path: /subdir1/subdir2/subdir3/subdir4/ is exactly where I want to iterate.

Debugging reveals that juc is indeed created correctly and pointing to the correct path. jarFile then as expected, just gives me the jar file path which is why I lose the subdirectories and why I start iterating at the root. This all makes sense. This clearly isn't the correct way. There has to be another way!

Messing around with the JarURLConnection which theoretically points to the correct directory I am interested in, doesn't reveal anything useful. There is JarURLConnection.getInputStream(). Debugger indicates that this ultimately holds a ZipFileInputStream, but I can't get access to it, and looking further it looks like its just the ZipFileInputStream to the ZipFile - which puts me back at square one.

回答1:

sorry, there isn't another way, at least not with the standard java libraries. a zip file just contains a list of entries, there is no "random access" lookup in it. there may be other libraries out there that parse through the list for you and create some sort of hierarchical map of entries, but either way, some code needs to iterate through all the entries to find what you need.