Pretty much what the title asks.
Say I'm passed a Path of "/tmp/foo/bar" and I want to specifically ensure that that path is a subdirectory of a path "/tmp", what is the most "Java 8"ish way of going about this?
Specifically I am interested in asking "Given two independent paths, /foo and /foo/bar/baz how can I test if /foo/bar/baz is a subdirectory of /foo without recursing the directory tree?" I am not interested in exploring all the sub directories under /foo and finding /foo/bar/baz downstream.
I've been playing with the idea of
@Test
public void test() {
final Path root = Paths.get("/tmp");
final Path path0 = Paths.get("/");
final Path path1 = Paths.get("/opt/location/sub");
final Path path2 = Paths.get("/tmp/location/sub");
final Pattern ptrn = Pattern.compile("^[a-zA-Z].*$");
final Function<Path, String> f = p -> root.relativize(p).toString();
Assert.assertFalse("root",ptrn.matcher(f.apply(root)).matches());
Assert.assertFalse("path0",ptrn.matcher(f.apply(path0)).matches());
Assert.assertFalse("path1",ptrn.matcher(f.apply(path1)).matches());
Assert.assertTrue("path2",ptrn.matcher(f.apply(path2)).matches());
}
but this feels like I worked right up to the edge of Java 8 and then dove back to old patterns and missed the boat.
boolean startsWith(Path other)
Tests if this path starts with the given path.