[英]How do you list all files in the Resources folder (java/scala)
I am writing a function which needs to access a folder in the resources, and loop through all filenames, and if those match the criteria, those files are loaded.我正在编写一个函数,它需要访问资源中的一个文件夹,并循环遍历所有文件名,如果这些文件名符合条件,则加载这些文件。
new File(getClass.getResource("/images/sprites").getPath).listFiles()
returns a null pointer exception, where the directory tree follows Resources -> images -> sprites ->返回空指针异常,其中目录树遵循Resources -> images -> sprites ->
Please can somebody point me in the right direction?请有人能指出我正确的方向吗?
A zip file system using jar:file:
URIs would be something like this:使用jar:file:
URI 的 zip 文件系统将是这样的:
URI uri = MainApp.class.getResource("/images/sprites").toURI();
Map<String, String> env = new HashMap<>();
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
//Path path = zipfs.getPath("/images/icons16");
for (Path path : zipfs.getRootDirectories()) {
Files.list(path.resolve("/images/sprites"))
.forEach(p -> System.out.println("* " + p));
}
}
Here I show getRootDirectories
to possibly iterate over all resources.在这里,我展示了getRootDirectories
可能会遍历所有资源。
Using the Files.copy
one may copy them etcetera.使用Files.copy
可以复制它们等等。
After comment of @MrPowerGamerBR:在@MrPowerGamerBR 发表评论后:
The solution above deals with a jar .上面的解决方案处理jar 。 A more general solution, not exposing the jar character, is:不暴露 jar 字符的更通用的解决方案是:
URI uri = MAinApp.class.getResource("/images/sprites"").toURI();
Path dirPath = Paths.get(uri);
Files.list(dirPath)
.forEach(p -> System.out.println("* " + p));
(In fact one might even read lines from the directory itself, but this is the correct abstraction, using Path .) (事实上,人们甚至可以从目录本身读取行,但这是正确的抽象,使用Path 。)
Joop Eggen's answer is awesome, however it can only do one of two things: Joop Eggen 的回答很棒,但它只能做两件事之一:
So here's a example (Kotlin, but it should be easy to migrate it to Java) that allows you to have both: Reading the resources content when running from a IDE or via the command line!所以这里有一个示例(Kotlin,但它应该很容易迁移到 Java),它允许您同时拥有:从 IDE 或通过命令行运行时读取资源内容!
val uri = MainApp::class.java.getResource("/locales/").toURI()
val dirPath = try {
Paths.get(uri)
} catch (e: FileSystemNotFoundException) {
// If this is thrown, then it means that we are running the JAR directly (example: not from an IDE)
val env = mutableMapOf<String, String>()
FileSystems.newFileSystem(uri, env).getPath("/locales/")
}
Files.list(dirPath).forEach {
println(it.fileName)
if (it.fileName.toString().endsWith("txt")) {
println("Result:")
println(Files.readString(it))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.