Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java listFiles in directory in jar

Tags:

java

io

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.

like image 683
dirtymikeandtheboys Avatar asked Sep 12 '25 18:09

dirtymikeandtheboys


1 Answers

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.
like image 150
VGR Avatar answered Sep 15 '25 09:09

VGR