Using DirectoryStreams in Java 7

Java 7 comes with lot’s of new stuff for IO. The new interfaces and classes added to the java.nio package contain lot’s of useful functionality for working with files and other things like asynchronous IO.

Here I want to show you a little bit about the interface DirectoryStream which is very useful when you want to work with the content of a directory (e.g. the files it contains).

In order to create a new Directory Stream you use one of the methods in the new utility class java.nio.file.Files. This method contains tons of useful methods for working with files and directories. A few let you create a new DirectoryStream. This interface can be used like a collection because it extends Iterable. That is you can use it in a for like this:
for (Path p : directoryStream)
which is very convenient.

Below are a few methods that show you how to use a directory stream:

First we define a simple utility methods:

This method just iterates over a DirectoryStream and prints out the filename. The interface Path is also new in Java 7 and represents a file system path like a file or a directory. It also contains a huge amount of useful methods. Make sure to check it out.

Here is a method that prints the file name for all files in a given directory (it does not walk into subdirectories. For this you will need the FileVisitor interface, which I will describe in an upcoming post).

This method is very simple. It just creates a new DirectoryStream and then calls the method printStreamInfo shown above. The code uses the Try with resources feature that comes with Java 7. You can also catch a DirectoryIteratorException which is a RunTimeException thrown when there is an error iterating over the DirectoryStream

Here is another, very similar method:

The difference here is the glob pattern. You can use it do show only files that correspond to a special pattern. For example to only list all the Ruby files in your directory, use "*rb". To show both Python and Ruby files, you can use "*.{rb,py}". There are many more patterns available. See here for a detailed documentation:

You can call the above method like this:

The last example uses the DirectoryStream.Filter interface to list only files that are larger that a given amount of kilobytes.
This interface defines only the method accept(T entry) which returns true of an entry confirms to the rules specified by the filter.

As you can see, using the new DirectoryStream and DirectoryStream.Filter is very simple. All the new methods, classes and interfaces added to Java 7 for file IO make working with files very easy and convenient. If you already use Java 7 and have to work with files, make sure to have a close look.

A much more detailed documentation can be found in the Java Tutorial for Java 7 on the Oracle website:
File I/O (Featuring NIO.2)

Leave a Reply

This blog is kept spam free by WP-SpamFree.