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

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

    It's a tree, so recursion is your friend: start with the parent directory and call the method to get an array of child Files. Iterate through the child array. If the current value is a directory, pass it to a recursive call of your method. If not, process the leaf file appropriately.

    0 讨论(0)
  • 2020-11-22 09:24

    To add with @msandiford answer, as most of the times when a file tree is walked u may want to execute a function as a directory or any particular file is visited. If u are reluctant to using streams. The following methods overridden can be implemented

    Files.walkFileTree(Paths.get(Krawl.INDEXPATH), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
        new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                    throws IOException {
                    // Do someting before directory visit
                    return FileVisitResult.CONTINUE;
            }
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
                    // Do something when a file is visited
                    return FileVisitResult.CONTINUE;
            }
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                    throws IOException {
                    // Do Something after directory visit 
                    return FileVisitResult.CONTINUE;
            }
    });
    
    0 讨论(0)
  • 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<Path> fv = new SimpleFileVisitor<Path>() {
          @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<Path> paths = Files.walk(Paths.get("/usr"))) {
          paths.forEach(System.out::println);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    
    }
    
    0 讨论(0)
  • 2020-11-22 09:29

    Check out the FileUtils class in Apache Commons - specifically iterateFiles:

    Allows iteration over the files in given directory (and optionally its subdirectories).

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