0

How to recursively list all text files in a directory?

Share:

In this example you’ll learn how to use the Files.walkFileTree() to walk through file tree. This method requires two parameters. The first parameter is the starting file, in this example we’ll start from drive D:. And the second parameter is the file visitor to invoke for each file. Here we’ll create a file visitor call FindTextFilesVisitor which extend the java.nio.file.SimpleFileVisitor.

To get all the text files (files end with .txt) we override the visitFile() defined by the SimpleFileVisitor. In this method we check if the file ends with .txt extension and print the file name when the extension match. And we continue to walk the file tree by returning FileVisitResult.CONTINUE.

Instead of listing files, you can modify the code snippet above for instance use it to delete all the files that ends with .bak. Simply change the extension and replace the print out statement with a file delete statement in the visitFile() method.

Filed in: Java IO

Leave a Reply

Submit Comment

© 2014 Java Examples - Developed with