简体   繁体   English

JAR目录中的Java listFiles

[英]Java listFiles in directory in jar

Is there any way to use listFiles() on a directory that's been packaged into a jar? 有没有办法在打包到jar中的目录上使用listFiles()

Let's say I have a directory in my resource directory with some text files: texts/text1.txt and texts/text2.txt . 假设我的资源目录中有一个目录,其中包含一些文本文件: texts/text1.txttexts/text2.txt

And within this Java program I have a class that needs to use listFiles() to get a list of those files. 在此Java程序中,我有一个需要使用listFiles()获取这些文件列表的类。 I'll get something like jar:file:/home/soupkitchen.jar/!text . 我会得到像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? 有什么方法可以将其视为包含文件的java.io.File目录? Right now it seems to only be listed as neither a file nor directory. 现在,它似乎只被列出为文件和目录。

No. java.io.File can only be used to list real directories. 不可以。java.io.File仅可用于列出真实目录。

However, you can treat it as a java.nio.file.Path. 但是,您可以将其视为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 . 将.jar作为Zip文件系统打开,并使用Files.newDirectoryStreamFiles.list
  2. Iterate through all entries in the .jar file, looking for names that match. 遍历.jar文件中的所有条目,以查找匹配的名称。
  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. 在您的.jar文件中放置一个文本文件,其中包含目录中所有条目的名称,因此您不必尝试列出它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM