简体   繁体   中英

How do you list all files in the Resources folder (java/scala)

I am writing a function which needs to access a folder in the resources, and loop through all filenames, and if those match the criteria, those files are loaded.

new File(getClass.getResource("/images/sprites").getPath).listFiles()

returns a null pointer exception, where the directory tree follows Resources -> images -> sprites ->

Please can somebody point me in the right direction?

A zip file system using jar:file: URIs would be something like this:

    URI uri = MainApp.class.getResource("/images/sprites").toURI();
    Map<String, String> env = new HashMap<>();
    try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
        //Path path = zipfs.getPath("/images/icons16");
        for (Path path : zipfs.getRootDirectories()) {
            Files.list(path.resolve("/images/sprites"))
                    .forEach(p -> System.out.println("* " + p));
        }
    }

Here I show getRootDirectories to possibly iterate over all resources.

Using the Files.copy one may copy them etcetera.


After comment of @MrPowerGamerBR:

The solution above deals with a jar . A more general solution, not exposing the jar character, is:

    URI uri = MAinApp.class.getResource("/images/sprites"").toURI();
    Path dirPath = Paths.get(uri);
    Files.list(dirPath)
         .forEach(p -> System.out.println("* " + p));

(In fact one might even read lines from the directory itself, but this is the correct abstraction, using Path .)

Joop Eggen's answer is awesome, however it can only do one of two things:

  • Read the resources content when running from a IDE
  • Read the resources content when running the JAR via the command line

So here's a example (Kotlin, but it should be easy to migrate it to Java) that allows you to have both: Reading the resources content when running from a IDE or via the command line!

    val uri = MainApp::class.java.getResource("/locales/").toURI()
    val dirPath = try {
        Paths.get(uri)
    } catch (e: FileSystemNotFoundException) {
        // If this is thrown, then it means that we are running the JAR directly (example: not from an IDE)
        val env = mutableMapOf<String, String>()
        FileSystems.newFileSystem(uri, env).getPath("/locales/")
    }

    Files.list(dirPath).forEach {
        println(it.fileName)
        if (it.fileName.toString().endsWith("txt")) {
            println("Result:")
            println(Files.readString(it))
        }
    }

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