Java Path.normalize and relativize
Simplify redundant path components or calculate directions between two locations.
A simple example
Path.normalize and relativize
- Start with Path notes/./a.txt
- Do this Remove the redundant dot
- Result notes/a.txt
Syntax
Path normalize()
JDK 21 declarations (2)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaLink a lesson to its diagram
An author keeps lessons in a notes folder and diagrams in a sibling images folder. The course will move between computers, so the link should be relative to the lesson directory.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path notes = Path.of("course", "notes");
Path image = Path.of("course", "images", "map.png");
Path link = notes.relativize(image);
System.out.println(link.getName(0));
System.out.println(notes.resolve(link).normalize().equals(image));
}
}
.. true
The first step goes up to the course directory. Resolving the remaining steps reaches the diagram.
Simplify an unsaved course link
A course editor assembles a link from relative fragments before publishing the files. Remove the redundant current and parent components and check the resulting names without creating either folder.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path draft = Path.of("lessons", ".", "week1", "..", "index.txt");
System.out.println(draft.normalize().equals(Path.of("lessons", "index.txt")));
}
}
true
Lexical normalization works here before any target exists.
Locate a rehearsal score
The choir stores each score inside a season folder. A catalogue starts in the parent directory. Which relative link reaches the file in the named subfolder? Use forward slashes in this example.
What to watch for
Normalization works on names alone. A symbolic link followed by a parent component can change the meaning of a normalized path.