Wednesday, 5 September 2012

Java find files for a given extension, recursively

In a bit of code I was doing I wanted to run without depending on any external libraries. The trouble that I had was that I was using commons-io.



The problem was given a directory, find all jar files recursively. Commons IO solution:


Collection<File> jarFiles = FileUtils.listFiles(new File(root), new String[]{"jar"}, true);



Simple and clean. How would I do this in java? Wait a second, I'm using java 7 which has improvements to the IO. You know, called New IO 2, or NIO2. This will probably be even easier is what I thought. Well, below is the solution that I came up with after looking at many different blogs.


final Collection<File> jarFiles = new ArrayList<File>();

final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**/*.jar");
Files.walkFileTree(Paths.get(root), new SimpleFileVisitor<Path>() {

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (matcher.matches(file)) {
jarFiles.add(file.toFile());
}
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});



Close to 20 lines. Yuck. To be fair, it is super powerful with what kinds of different things that you do do with it, not just looking at the extensions, but man oh man is that a whole bunch of ugly. Why with java do you always have to use heaps of libraries and frameworks to get anything that even starts to look clean and tight?



No comments:

Post a Comment