如何列出Resources文件夹中的所有文件(java/scala)

mys*_*ter 2 java resources scala

我正在编写一个函数,需要访问资源中的文件夹,并循环遍历所有文件名,如果这些文件符合条件,则加载这些文件。

new File(getClass.getResource("/images/sprites").getPath).listFiles()
Run Code Online (Sandbox Code Playgroud)

返回空指针异常,其中目录树遵循Resources -> images -> sprites ->

请有人指出我正确的方向吗?

MrP*_*rBR 7

Joop Eggen 的答案很棒,但它只能做以下两件事之一:

  • 从IDE运行时读取资源内容
  • 通过命令行运行JAR时读取资源内容

因此,这里有一个示例(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))
        }
    }
Run Code Online (Sandbox Code Playgroud)


Joo*_*gen 5

使用 URI 的 zip 文件系统jar:file:将如下所示:

    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));
        }
    }
Run Code Online (Sandbox Code Playgroud)

在这里,我展示了getRootDirectories可能迭代所有资源的方法。

使用该Files.copy工具可能会复制它们等等。


@MrPowerGamerBR 评论后:

上面的解决方案涉及一个jar。一个更通用的解决方案,不暴露 jar 字符,是:

    URI uri = MAinApp.class.getResource("/images/sprites").toURI();
    Path dirPath = Paths.get(uri);
    Files.list(dirPath)
         .forEach(p -> System.out.println("* " + p));
Run Code Online (Sandbox Code Playgroud)

(事实上​​,人们甚至可以从目录本身读取行,但这是正确的抽象,使用Path。)