我正在编写一个需要访问资源中的文件夹的函数,并循环遍历所有文件名,如果符合条件,则会加载这些文件。
new File(getClass.getResource("/images/sprites").getPath).listFiles()
返回空指针异常,其中目录树遵循Resources - >图像 - >精灵 - >
请有人指出我正确的方向吗?
答案 0 :(得分:1)
使用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));
}
}
在这里,我展示getRootDirectories
可能会迭代所有资源。
使用Files.copy
可以复制它们等等。
答案 1 :(得分:0)
Joop Eggen 的回答很棒,但它只能做两件事之一:
这里有一个示例(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))
}
}