从 Resources 文件夹中获取文件夹 JAVA

Get folder from Resources folder JAVA

大家好我无法解决这个问题:这行代码应该可以工作

File[] file = (new File(getClass().getResource("resources/images_resultats"))).listFiles();

我想要一个文件列表,这些文件在 "resources" 下的 "images_resultats" 下。

如果 resources/images_resultats 不在你的类路径中and/or 如果它在 jar 文件中,它将无法工作。

您的代码甚至都不正确,应该类似于:

File[] file = (new File(getClass().getResource("/my/path").toURI())).listFiles();

假设资源文件夹在类路径中,这可能有效。

   String folder = getClass().getResource("images_resultats").getFile();
   File[] test = new File(folder).listFiles();

您可以使用文件系统 class.

确定资源文件夹中的文件(即使它在 jar 中)
public static void doSomethingWithResourcesFolder(String inResourcesPath) throws URISyntaxException {
    URI uri = ResourcesFolderUts.class.getResource(inResourcesPath).toURI();
    try( FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap() ) ){
        Path folderRootPath = fileSystem.getPath(inResourcesPath);
        Stream<Path> walk = Files.walk(folderRootPath, 1);
        walk.forEach(childFileOrFolder -> {
            //do something with the childFileOrFolder
        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

inResourcesPath 应该类似于 "/images_resultats"

请注意,childFileOrFolder 路径只能在文件系统保持打开时使用,如果您尝试(例如)return 路径然后稍后使用它们,您会遇到文件系统关闭异常。

为您自己的 classes

更改 ResourcesFolderUts