Java

Path Operations — Resolve, Relativize, Normalize

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`Path` (NIO) replaces `File` for new code. Operator-like methods compose paths cleanly across OSes — and the underlying file isn't touched until you do I/O.
Java
Raw
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());
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.