Monday, 9 August 2010

A Little Directory love

Hi all,

So my next little snippet also comes from Chapter 2 of the book where we deal with the new NIO.2 (Non-Blocking I/O 2) APIs being introduced to Java 7.  In particular I'm showing a small code snippet to showcase some of the new support for directories that Java 7 has.  The code sample certainly needs a little tidy-up by using the new Automatic Resource Management (ARM) features in Java 7, but for now the example will suffice.


Dealing with Directories

The java.nio.file.DirectoryStream interface and its implementing classes allow you to:

  • Iterate over entries in a directory.
  • Deal with large directory structures.
  • Filter entries whilst processing using regular expressions and MIME based content detection.
  • Walk the tree structure in order to perform recursive move, copy, delete operations.
A common use case here is to list entries in a directory, e.g. Java source files as shown by the listing below.

DirectoryStream stream = null;
try
{
    // Define the directory
    Path dir = Paths.get("c:\\workspace");

    // Declare a filtering stream
    stream = dir.newDirectoryStream("*.java");
    // List each .java file in that directory
    for (Path entry: stream)
    {
        System.out.println(entry.getName());
    }
}
catch (IOException e)
{
    // Poor man's exception handling
    e.printStackTrace();
}

As you can see, with the new Java 7 APIs this particular task is much simpler than it used to be and this theme is prevalent in the rest of the NIO.2 APIs.

There are several other use cases which we will show case in the "NIO.2 in action" section.as well as on our upcoming website (to be revealed later).


So are we there yet?  In terms of File and Directory interaction in Java 7 there's certainly a massive improvement, so I'll say "Yes" once Java 7 is released.

Cheers,
Martijn

1 comment:

  1. That still feels like a step too much though
    // Define the directory
    Path dir = Paths.get("c:\\workspace");
    // Declare a filtering stream
    stream = dir.newDirectoryStream("*.java");

    I would prefer something like

    Path dir = Paths.get("/workspace").filter(*.java);

    which could act as shorthand for the above. Also having a DirectoryStream feels clunky and counterintuitive. What's wrong with Path having Directories?

    ReplyDelete