Skip to content

Instantly share code, notes, and snippets.

@msgodf
Last active December 17, 2015 18:49
Show Gist options
  • Save msgodf/5656370 to your computer and use it in GitHub Desktop.
Save msgodf/5656370 to your computer and use it in GitHub Desktop.
Trying out Java 7 NIO2's FileVisitor, along with half of Guava to attempt a slightly functional style. This is still pretty verbose in Java.
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Function;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomains;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ranges;
public class TryingOutNIO2 {
public void someFunction() {
Path path = Paths.get("/tmp");
SimpleFileVisitor<Path> simpleFileVisitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path path, BasicFileAttributes attributes) throws IOException {
ContiguousSet<Integer> range = Ranges.closedOpen(0, path.getNameCount()).asSet(DiscreteDomains.integers());
String completePathAndFilename = StringUtils.join(
Iterables.transform(range, new Function<Integer, String>() {
@Override
public String apply(Integer x) {
return path.getName(x).toString();
}
}), "/");
System.out.println(completePathAndFilename);
return FileVisitResult.CONTINUE;
}
};
try {
Files.walkFileTree(path, simpleFileVisitor);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@msgodf
Copy link
Author

msgodf commented May 27, 2013

Just experimenting whilst reading Evans and Verburg's "The Well-Grounded Java Developer" (http://www.manning.com/evans/)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment