【问题标题】:Get folder from Resources folder JAVA从资源文件夹JAVA中获取文件夹
【发布时间】:2016-08-06 00:23:54
【问题描述】:

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

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

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

【问题讨论】:

  • 资源不是文件,在大多数情况下,它们是 zip 容器(jar 文件)中的条目,不能像文件一样访问或处理。以这种方式列出未知jar文件的内容非常困难
  • For example,第二种解决方案建议使用“已知”文件/资源​​,其中包含资源名称列表,可以在构建时生成
  • 如果jar中不包含该目录,应该可以直接使用相对路径

标签: java file src


【解决方案1】:

如果resources/images_resultats 不在您的类路径中和/或如果它在 jar 文件中,它将不起作用。

您的代码甚至不正确,应该是这样的:

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

【讨论】:

  • 所以我必须有一个文件夹,其中包含我的三个文件夹images_resultats 等...和.jar
【解决方案2】:

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

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

【讨论】:

  • 它返回一个java.lang.NullPointerException -> String folder = getClass().getResource("images_resultats").getFile();
  • getClass().getResource("images_resultats").getFile() 文件夹是否为空返回 null!
【解决方案3】:

您可以使用 FileSystem 类确定资源文件夹中的文件(即使它在 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 路径只能在文件系统保持打开状态时使用,如果您尝试(例如)返回路径然后稍后使用它们,您将获得文件系统关闭异常。

为您自己的一个类更改 ResourcesFolderUts

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-23
    • 2019-03-24
    • 2016-03-17
    • 2016-02-11
    • 1970-01-01
    • 2010-12-02
    • 2017-12-08
    相关资源
    最近更新 更多