How do I iterate through the files in a directory in Java?

前端 未结 10 2120
星月不相逢
星月不相逢 2020-11-22 08:37

I need to get a list of all the files in a directory, including files in all the sub-directories. What is the standard way to accomplish directory iteration with Java?

10条回答
  •  囚心锁ツ
    2020-11-22 09:04

    For Java 7+, there is also https://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html

    Example taken from the Javadoc:

    List listSourceFiles(Path dir) throws IOException {
       List result = new ArrayList<>();
       try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.{c,h,cpp,hpp,java}")) {
           for (Path entry: stream) {
               result.add(entry);
           }
       } catch (DirectoryIteratorException ex) {
           // I/O error encounted during the iteration, the cause is an IOException
           throw ex.getCause();
       }
       return result;
    }
    

提交回复
热议问题