Recursively list files in Java

后端 未结 27 1587
走了就别回头了
走了就别回头了 2020-11-22 00:29

How do I recursively list all files under a directory in Java? Does the framework provide any utility?

I saw a lot of hacky implementations. But none from the fra

相关标签:
27条回答
  • 2020-11-22 01:00

    Kotlin has FileTreeWalk for this purpose. For example:

    dataDir.walkTopDown().filter { !it.isDirectory }.joinToString("\n") {
       "${it.toRelativeString(dataDir)}: ${it.length()}"
    }
    

    Will produce a text list of all the non-directory files under a given root, one file per line with the path relative to the root and length.

    0 讨论(0)
  • 2020-11-22 01:01

    FileUtils have iterateFiles and listFiles methods. Give them a try. (from commons-io)

    Edit: You can check here for a benchmark of different approaches. It seems that the commons-io approach is slow, so pick some of the faster ones from here (if it matters)

    0 讨论(0)
  • 2020-11-22 01:01

    The accepted answer is great, however it breaks down when you want to do IO inside the lambda.

    Here is what you can do if your action declares IOExceptions.

    You can treat the filtered stream as an Iterable, and then do your action in a regular for-each loop. This way, you don't have to handle exceptions inside a lambda.

    try (Stream<Path> pathStream = Files.walk(Paths.get(path))
            .filter(Files::isRegularFile)) {
    
        for (Path file : (Iterable<Path>) pathStream::iterator) {
            // something that throws IOException
            Files.copy(file, System.out);
        }
    }
    

    Found that trick here: https://stackoverflow.com/a/32668807/1207791

    0 讨论(0)
提交回复
热议问题