Library contents

Java Path locations and real paths

Distinguish relative names, absolute addresses, and resolved locations on an existing file system.

A simple example

Path locations and real paths

  1. Start with Current folder /work, relative file a
  2. Do this Make the path absolute
  3. Result /work/a
In this Unix-style example the current directory supplies the missing beginning of the path.

Syntax

Java syntax
boolean isAbsolute()
JDK 21 declarations (5)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Locate the current workshop folder

A workshop application receives a short filename from a participant. It needs to distinguish that name from an absolute address and learn which separator its provider uses for display.

From the programPath local = Path.of("register.csv")
First output linefalse
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path local = Path.of("register.csv");
        Path full = local.toAbsolutePath();
        System.out.println(local.isAbsolute());
        System.out.println(full.getRoot() != null);
        System.out.println(!local.getFileSystem().getSeparator().isEmpty());
    }
}
Output
false
true
true

The absolute form has a root even when the named file has not been created.

Advertisements

Resolve an existing classroom folder

A classroom app records the actual location of a newly created workspace. Its log should identify the same directory whether the input includes a current-directory component or uses the direct path.

Resulttrue
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            Path room = Files.createDirectory(desk.resolve("classroom"));
            Path actual = room.resolve(".").toRealPath();
            System.out.println(actual.equals(room.toRealPath()));
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
true

Both inputs resolve to the same real path on this file system.

Locate a rehearsal score

The choir stores each score inside a season folder. Resolve the child name against the absolute working folder. What final filename can the desk recover from the absolute result?

Givenspring / alto.txt
Worked resultalto.txt

What to watch for

toRealPath needs an accessible existing entry. File systems can differ in their roots, separators and supported features.

Documentation for Path locations and real paths