Java IO – File Listing and directory walking

The following use cases are covered in this tutorial.

  • Listing all files in a directory
  • Listing files of a specific type in a directory
  • Listing files with name matching a string
  • Walking a directory tree with handlers for each file or directory walked

Introduction

Java NIO introduced the walk file tree method that is extremely powerful. It uses the visitor pattern and can accomplish almost anything. However, convenient methods exist in apache commons io that accomplish the same task with minimum coding. Apache commons io has special prebuilt file filters that can be used to list specific files. Use NIO if you want more control over what you want to do with the files in a directory and use apache commons if you have standard file listing tasks.

File Listing using java.io.File

We first demonstrate the methods in java.io.File. dir is of type java.io.File

List selected files in a directory. Uses a file filter implemented as an anonymous inner class.

File Listing and File tree walking using java.nio.file.Files

Use a directory stream to iterate over all the files in a directory. The directory stream implements iterable. It does not support all the operations that a normal iterable supports. For example, it does not support the remove operation. The files returned are not in any specific order.

java.nio.file.Files has a method
walkFileTree
that walks a file tree. The walk is depth first. A Visitor object is passed to each file in the path. In the example below we show a variant that does not follow symbolic links and visits all levels of the file tree. Here’s an example of the visitor. The File Visitor implements methods for a pre and post directory visit. It has method for a file visit. When a file visit fails a method called visitFileFailed is called. Each method returns a result of type FileVisitResult. The results are CONTINUE, TERMINATE, SKIP_SIBLINGS and SKIP_SUBTREE. return FileVisitResult.CONTINUE to continue traversing else use one of the other three tyes as applicable.

File Listing using org.apache.commons.io.FileUtils

The method listFiles Lists all files in a directory that match the FileFilters

This method uses two filters. The first filters files and the second filters directories. TrueFileFilter.INSTANCE matches all directories. To ignore cvs directories use FileFilterUtils.makeCVSAware(null). To find files in a directory that matches an array of extension pass an array of file extension strings. The last parameter is boolean and specifies whether subdirectories should also be searched.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.