Last active
December 17, 2015 18:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just experimenting whilst reading Evans and Verburg's "The Well-Grounded Java Developer" (http://www.manning.com/evans/)