Library contents

Java Path.normalize and relativize

Simplify redundant path components or calculate directions between two locations.

A simple example

Path.normalize and relativize

  1. Start with Path notes/./a.txt
  2. Do this Remove the redundant dot
  3. Result notes/a.txt
Normalization simplifies this spelling without needing to read the file.

Syntax

Java 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.java

Link 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.

From the programPath notes = Path.of("course", "notes")
First output line..
Main.java
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));
    }
}
Output
..
true

The first step goes up to the course directory. Resolving the remaining steps reaches the diagram.

Advertisements

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.

From the programPath draft = Path.of("lessons", ".", "week1", "..", "index.txt")
Resulttrue
Main.java
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")));
    }
}
Output
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.

Givenspring / alto.txt
Worked resultspring/alto.txt

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.

Documentation for Path.normalize and relativize