Java listFiles in directory in jar

2.7k views Asked by At

Is there any way to use listFiles() on a directory that's been packaged into a jar?

Let's say I have a directory in my resource directory with some text files: texts/text1.txt and texts/text2.txt.

And within this Java program I have a class that needs to use listFiles() to get a list of those files. I'll get something like jar:file:/home/soupkitchen.jar/!text. I'd expect that to be a directory. Is there any way to be able to treat it as a java.io.File directory containing files? Right now it seems to only be listed as neither a file nor directory.

1

There are 1 answers

2
VGR On BEST ANSWER

No. java.io.File can only be used to list real directories.

However, you can treat it as a java.nio.file.Path.

Overall, you have three options:

  1. Open the .jar as a Zip File System and use Files.newDirectoryStream or Files.list.
  2. Iterate through all entries in the .jar file, looking for names that match.
  3. Put a text file in your .jar that contains the names of all the entries in the directory, so you don't have to try to list them.