Recursively list files in Java

后端 未结 27 1592
走了就别回头了
走了就别回头了 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 00:57

    With Java 7 you can use the following class:

    import java.io.IOException;
    import java.nio.file.FileVisitResult;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.SimpleFileVisitor;
    import java.nio.file.attribute.BasicFileAttributes;
    
    public class MyFileIterator extends SimpleFileVisitor
    {
        public MyFileIterator(String path) throws Exception
        {
            Files.walkFileTree(Paths.get(path), this);
        }
    
        @Override
        public FileVisitResult visitFile(Path file,
                BasicFileAttributes attributes) throws IOException
        {
            System.out.println("File: " + file);
            return FileVisitResult.CONTINUE;
        }
    
        @Override
        public FileVisitResult preVisitDirectory(Path dir,
                BasicFileAttributes attributes) throws IOException
        {
            System.out.println("Dir: " + dir);
            return FileVisitResult.CONTINUE;
        }
    }
    

提交回复
热议问题