问题描述
有没有办法在打包到jar的目录中使用 listFiles()
?
Is there any way to use listFiles()
on a directory that's been packaged into a jar?
假设我的资源目录中有一个目录,其中包含一些文本文件: texts / text1.txt
和 texts / text2.txt
。
Let's say I have a directory in my resource directory with some text files: texts/text1.txt
and texts/text2.txt
.
在这个Java程序中,我有一个类需要使用 listFiles()
来获取这些文件的列表。我会得到像 jar:file:/home/soupkitchen.jar/!text
。我希望这是一个目录。有没有办法将它作为包含文件的 java.io.File
目录处理?现在它似乎只被列为既不是文件也不是目录。
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.
推荐答案
没有。 java.io.File只能用于列出真实目录。
No. java.io.File can only be used to list real directories.
但是,您可以将其视为java.nio.file.Path。
However, you can treat it as a java.nio.file.Path.
总的来说,您有三种选择:
Overall, you have three options:
- 打开.jar作为并使用或。
- 遍历.jar文件中的所有条目,查找匹配的名称。
- 放置文本.jar中包含目录中所有条目名称的文件,因此您不必尝试列出它们。
- Open the .jar as a Zip File System and use Files.newDirectoryStream or Files.list.
- Iterate through all entries in the .jar file, looking for names that match.
- 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中的Java listFiles目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!