在Java中如何遍历目录中的所有文件

代码示例

//-> IO
for (File selectedFile : folder.listFiles()) {
      //Note: Depending on the number of files in the directory folder.listFiles() Jan take a long time to return
      System.out.println((selectedFile.isDirectory() ? "d" : "f") + " " + selectedFile.getAbsolutePath());
}

//-> NIO
Files.walkFileTree(directory, EnumSet.noneOf(FileVisitOption.class), 1, new
SimpleFileVisitor() {
      @Override
      public FileVisitResult preVisitDirectory(Path selectedPath,   BasicFileAttributes attrs) throws IOException {
            System.out.println("d " + selectedPath.toAbsolutePath());
            return FileVisitResult.CONTINUE;
       }
       @Override
       public FileVisitResult visitFile(Path selectedPath, BasicFileAttributes attrs) throws
IOException {
            System.out.println("f " + selectedPath.toAbsolutePath());
            return FileVisitResult.CONTINUE;
       }
});
日期:2020-06-02 22:15:22 来源:oir作者:oir