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
- Start with Current folder /work, relative file a
- Do this Make the path absolute
- Result /work/a
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.javaLocate 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.
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());
}
}
false true true
The absolute form has a root even when the named file has not been created.
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.
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);
}
}
}
}
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?
What to watch for
toRealPath needs an accessible existing entry. File systems can differ in their roots, separators and supported features.