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

String[] everythingInThisDir = dir.list();
for (String name : everythingInThisDir) {
	System.out.println(name);
}

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

	File[] selectedFiles = dir.listFiles(new FileFilter() {
	  @Override
	  public boolean accept(File pathname) {
		if ("java-io".equals(pathname.getName()))
			return true;
		return false;
	  }
     });
for (File selectedFile : selectedFiles) {
	System.out.println(selectedFile.getAbsolutePath());
}

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.

 	DirectoryStream<Path> stream = Files.newDirectoryStream(tempDir);
    Iterator<Path> iter = stream.iterator();
    while (iter.hasNext()) {
	  Path path = iter.next();
    }

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.

		Files.walkFileTree(FileSystems.getDefault().getPath("dir"), new FileVisitor<Path>() {
            // Called after a directory visit is complete.
			@Override
			public FileVisitResult postVisitDirectory(Path dir, IOException exc)
					throws IOException {
				System.out
						.println("FilesExample.main(...).new FileVisitor() {...}.postVisitDirectory()");
				System.out.println(dir.getFileName());
				return FileVisitResult.CONTINUE;
			}
            // called before a directory visit.
			@Override
			public FileVisitResult preVisitDirectory(Path dir,
					BasicFileAttributes attrs) throws IOException {
				System.out
						.println("FilesExample.main(...).new FileVisitor() {...}.preVisitDirectory()");
				System.out.println(dir.getFileName());
				return FileVisitResult.CONTINUE;
			}
            // This method is called for each file visited. The basic attributes of the files are also available.
			@Override
			public FileVisitResult visitFile(Path file,
					BasicFileAttributes attrs) throws IOException {
				System.out
						.println("FilesExample.main(...).new FileVisitor() {...}.visitFile()");
				System.out.println(file.getFileName());
				return FileVisitResult.CONTINUE;
			}
           // if the file visit fails for any reason, the visitFileFailed method is called.
			@Override
			public FileVisitResult visitFileFailed(Path file, IOException exc)
					throws IOException {
				System.out
						.println("FilesExample.main(...).new FileVisitor() {...}.visitFileFailed()");
				System.out.println(file.getFileName());
				return FileVisitResult.CONTINUE;
			}
});

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

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

		Collection<File> files = FileUtils.listFiles(FileUtils.getFile("dir"), 
                 FileFilterUtils.suffixFileFilter(".txt"), TrueFileFilter.INSTANCE);

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.

Collection<File> filesb =
         FileUtils.listFiles(FileUtils.getFile("dir"), new String[] {"txt","jar"},true);]]>

Leave a Comment