7

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".

Project image

GHajba
  • 3,665
  • 5
  • 25
  • 35
Arnauld Alex
  • 339
  • 1
  • 3
  • 13
  • Resources are not files, in most cases they are entries in a zip container (the jar file) and not be accessed or treated like files. It is very difficult to list the contents of an unknown jar file in this manner – MadProgrammer Apr 14 '16 at 12:39
  • [For example](http://stackoverflow.com/questions/18758105/how-can-i-count-the-number-of-files-in-a-folder-within-a-jar/18758724#18758724), the second solution suggests using a "known" file/resource which contains a list of the resources names, which could be generated at build time – MadProgrammer Apr 14 '16 at 12:43
  • If the directory is not included in the jar, you should be able to use a relative path directly – MadProgrammer Apr 14 '16 at 12:45

3 Answers3

3

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();
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
1

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

Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
-3

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

   String folder = getClass().getResource("images_resultats").getFile();
   File[] test = new File(folder).listFiles();
s_u_f
  • 200
  • 1
  • 12