Adding And Substracting Path Instances With Java 📎
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
public class PathTest {
@Test
public void addPath() {
Path javaFile = Paths.get("com", "airhacks", "PathsTest.java");
Path root = Paths.get("src", "main", "java");
Path absolute = root.resolve(javaFile);
String expected = "src/main/java/com/airhacks/PathsTest.java";
String actual = absolute.toString();
assertThat(actual, is(expected));
}
@Test
public void substractPath() {
Path absolute = Paths.get("src/main/java/com/airhacks/PathsTest.java");
Path root = Paths.get("src", "main", "java");
Path relative = root.relativize(absolute);
//ignoring the OS-specific separator
String expected = "com/airhacks/PathsTest.java";
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: airhacks.io.