import java.nio.file.*;
class Demo {
void example() {
Path base = Path.of("/var/www/myapp");
// Resolve — append a relative path
Path config = base.resolve("config/app.toml");
System.out.println(config); // /var/www/myapp/config/app.toml
// Resolve with absolute → returns the absolute path as-is
Path abs = base.resolve("/etc/hosts");
System.out.println(abs); // /etc/hosts
// Relativize — inverse of resolve
Path a = Path.of("/var/www/myapp/config/app.toml");
Path b = Path.of("/var/www/myapp");
System.out.println(b.relativize(a)); // config/app.toml
// Normalize — collapse "." and ".."
Path messy = Path.of("/var/www/./myapp/../other/index.html");
System.out.println(messy.normalize()); // /var/other/index.html
// Components
System.out.println(config.getFileName()); // app.toml
System.out.println(config.getParent()); // /var/www/myapp/config
System.out.println(config.getNameCount()); // 4
// To absolute / toRealPath (resolves symlinks)
Path rel = Path.of("README.md");
System.out.println(rel.toAbsolutePath());
}
}
Create a free account and build your private vault. Share publicly whenever you want.