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

前端 未结 10 2315
星月不相逢
星月不相逢 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:29

    If you are using Java 1.7, you can use java.nio.file.Files.walkFileTree(...).

    For example:

    public class WalkFileTreeExample {
    
      public static void main(String[] args) {
        Path p = Paths.get("/usr");
        FileVisitor fv = new SimpleFileVisitor() {
          @Override
          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
              throws IOException {
            System.out.println(file);
            return FileVisitResult.CONTINUE;
          }
        };
    
        try {
          Files.walkFileTree(p, fv);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    
    }
    

    If you are using Java 8, you can use the stream interface with java.nio.file.Files.walk(...):

    public class WalkFileTreeExample {
    
      public static void main(String[] args) {
        try (Stream paths = Files.walk(Paths.get("/usr"))) {
          paths.forEach(System.out::println);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    
    }
    

提交回复
热议问题