簡體   English   中英

從資源文件夾 JAVA 中獲取文件夾

[英]Get folder from Resources folder JAVA

大家好,我無法解決這個問題:這行代碼應該可以工作

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

我想要一個文件列表,這些文件在“資源”下的“images_resultats”下。

項目圖片

如果resources/images_resultats不在您的類路徑中和/或如果它在 jar 文件中,它將不起作用。

您的代碼甚至不正確,它應該類似於:

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

您可以使用 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 路徑只能在 FileSystem 保持打開狀態時使用,如果您嘗試(例如)返回路徑然后稍后使用它們,則會出現文件系統關閉異常。

為您自己的類之一更改 ResourcesFolderUts

假設資源文件夾在類路徑中,這可能會起作用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM