Adam Bien's Weblog

Adding And Substracting Path Instances With Java

Method resolve adds Path instances and is useful to create absolute paths. The method relativize substracts Path instances and is useful to remove the root component from the absolute path:

import java.nio.file.Path;
import java.nio.file.Paths;
import static;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class PathTest {

    public void addPath() {
        Path javaFile = Paths.get("com", "airhacks", "");
        Path root = Paths.get("src", "main", "java");

        Path absolute = root.resolve(javaFile);

        String expected = "src/main/java/com/airhacks/";
        String actual = absolute.toString();
        assertThat(actual, is(expected));

    public void substractPath() {
        Path absolute = Paths.get("src/main/java/com/airhacks/");
        Path root = Paths.get("src", "main", "java");

        Path relative = root.relativize(absolute);

	//ignoring the OS-specific separator
        String expected = "com/airhacks/";
        String actual = relative.toString();
        assertThat(actual, is(expected));


See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home:

NEW workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.


A book about rethinking Java EE Patterns


Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments