Tallan's Technology Blog

Tallan's Top Technologists Share Their Thoughts on Today's Technology Challenges

Java 7 File IO using FileVisitor

Richard Krajunus

This blog post is inspired by a problem a friend of mine was having. See… he’s got this rash… -kidding. He’s got a ton of movies, music, and books on his hard drive, and he frequently rearranges the directory structure of his drive to better organize his media. He wanted to create snapshots of his folder arrangement so that he could refer to it later. This post highlights issues I had implementing a simple solution using Java 7s new NIO.2 package.

I started by going through file IO tutorials and was excited to see new documentation on recursive directory traversal for Java 7. The documentation was clear and complete, so I won’t rehash the entire tutorial here, but I will talk about a couple of snags I tripped up on along the way.

First, if you don’t have adequate permissions to access all the directories that you’ll be visiting, then you’ll need to implement visitFileFailed(). My implementation was pretty trivial:

/* If there is some error accessing the file, skip it and continue on.  If you
 * don't override this method and an error occurs, an IOException is thrown.
 */
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
    return CONTINUE;
}

Second, is that when I ran the program on a Mac I noticed that for a directory with many subdirectories (close to 700, in this case), the application was only traversing about half of them. The original structure of the program was to write each directory to a list, and then write the contents of the list to a file. To resolve this, I modified the structure to output the directory to the console by overriding postVisitDirectory(...):

@Override
public FileVisitResult postVisitDirectory(Path dir, BasicFileAttributes attr) {
    System.out.println(dir.toAbsolutePath().toString());
}

and then redirecting the output of the program from the shell to a file, as in:
> java ListDirectories '/the/root/folder' > outputFile.txt

The resulting file had all the output (140K+ directories).

Tags: How To Guide,

No comments

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

\\\