adam bien's blog

Paths "Subtraction" with Path#relativize 📎

The method relativize computes the difference between an absolute path (src/main/java/com/airhacks) and it's root (src/main/java). This is useful for subtraction of a common path prefix:

import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Test;

public class PathSubstractionTest {

    @Test
    public void splitWithDot() {
        Path fromProjectRoot = Paths.get("src/main/java/com/airhacks");
        Path projectRoot = Paths.get("src/main/java");
        Path substracted = projectRoot.relativize(fromProjectRoot);
        String actual = substracted.toString();
        String expected = "com/airhacks";
        assertThat(actual, is(expected));
    }
}