Home > database >  How can I get all the directories within a jar as a List of File objects?
How can I get all the directories within a jar as a List of File objects?

Time:12-17

I have a jar which has a resources folder that contains a folder, let's call it toplevel. toplevel contains another folder, called level1. level1 then contains a list of directories. I'd like to retrieve these directories as java.io.File objects, so that another function can do things with these File objects. With the below example that'd be a List<File> like List{dira, dirb, dirc} How can this be done?


toplevel

---level1

------dir a

------dir b

------dir c

CodePudding user response:

I would suggest extracting matching entries from the jar file and save to a temporary location to get the java.io.File reference.

Option #1:

If you are reading from a file system, use ZipFile to read the file then use ZipFile.getEntry("zip-path") to get the entry and save using Files.copy

See: enter image description here

See Example Implementation in:

<script src="https://gist.github.com/nfet/27fce2870b8cd42e3337f6a21b8e9711.js"></script>

CodePudding user response:

Thanks for the help folks but after much ado, found a solution working atop this previous solution https://stackoverflow.com/a/1529707/9486041 to narrow down to the folders and its contents.

JarURLConnection connection = (JarURLConnection) folderURL.openConnection()
JarFile jar = new JarFile(new File(connection.getJarFileURL().toURI()))
Enumeration enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
    JarEntry file = (JarEntry) enumEntries.nextElement();
    if (!file.name.startsWith(path   "/")) {
        continue
    }
    File f = new File(System.getProperty("user.home")   "/tmp"   File.separator   file.getName());
    f.getParentFile().mkdirs()
    
    InputStream is = jar.getInputStream(file); // get the input stream
    FileOutputStream fos = new FileOutputStream(f);
    while (is.available() > 0) {  // write contents of 'is' to 'fos'
        fos.write(is.read());
    }
    fos.close();
    is.close();

}
jar.close()
  • Related