Recursively find all text files in directory

前端 未结 3 605
离开以前
离开以前 2020-12-10 21:31

I am trying to get the names of all of the text files in a directory. If the directory has subdirectories then I also want to get any text files in those as well. I am not s

相关标签:
3条回答
  • 2020-12-10 22:17

    The answer is in the tags of your question. Use recursion. Recursion consists in having a method call itself.

    In this case, the method should print all the text files directly under a given directory, and call itself for every subdirectory of the directory.

    0 讨论(0)
  • 2020-12-10 22:18

    This is a recursive problem

    public void find_files(File root)
    {
        File[] files = root.listFiles(); 
        for (File file : files) {
            if (file.isFile()) {
                ...
            } else if (file.isDirectory()) {
                find_files(file);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-10 22:20

    using the java.nio.file capabilites of java 7. I implemented similiar func. and added some test.

    Benchmarks when searching for .txt on my PC

                "c:/"  "c:/windows"
    file.io   36272ms       14082ms
    file.nio   7167ms        2987ms  
    

    Read more in the javadoc, it's quite powerfull API

    java.nio.file.filevisitor javadoc

    public static void main(String[] args) {
        long starttime = System.currentTimeMillis();
        try {
            Path startPath = Paths.get("c:/");
            Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir,
                        BasicFileAttributes attrs) {
                    System.out.println("Dir: " + dir.toString());
                    return FileVisitResult.CONTINUE;
                }
    
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                    if (file.toString().endsWith(".txt")){
                        System.out.println(file.toString());    
                    }
                    return FileVisitResult.CONTINUE;
                }
    
                @Override
                public FileVisitResult visitFileFailed(Path file, IOException e) {
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long completetime = System.currentTimeMillis() - starttime;
        System.out.println("totaltime=" + completetime);
    
    }
    
    0 讨论(0)
提交回复
热议问题