简体   繁体   中英

Get folder from Resources folder JAVA

Hi everyone I can't figure out with this problem : this line of code should work

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

I want a list of File, these Files are under "images_resultats" under "resources".

项目图片

It won't work if resources/images_resultats is not in your classpath and/or if it is in a jar file.

Your code is not even correct it should something like:

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

You can determine what files are in a folder in resources (even if its in a jar) using the FileSystem class.

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 should be something like "/images_resultats"

Note that the childFileOrFolder paths can only be used while the FileSystem remains open, if you try to (for example) return the paths then use them later you've get a file system closed exception.

Change ResourcesFolderUts for one of your own classes

Assuming that resources folder is in classpath, this might work.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM