Java File absolute and canonical paths
Produce an absolute pathname or ask the system for its canonical spelling.
A simple example
File absolute and canonical paths
- Start with An existing file a.txt in the current folder
- Do this Resolve ./a.txt and a.txt
- Result Same canonical file
Syntax
public 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.javaReconcile two spellings in an export log
A school keeps a list of folders used for report exports. One entry contains a dot component, so the clerk needs to check whether it identifies the same canonical folder as the direct spelling.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
File folder = desk.toFile();
File spelling = new File(folder, ".");
System.out.println(spelling.isAbsolute());
System.out.println(spelling.getAbsoluteFile().getPath().equals(spelling.getAbsolutePath()));
System.out.println(spelling.getCanonicalFile().equals(folder.getCanonicalFile()));
System.out.println(spelling.getCanonicalPath().equals(folder.getCanonicalPath()));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true true true true
Absolute conversion keeps an address usable from any working directory. Canonical conversion reconciles the two spellings.
Resolve a path before the draft exists
A report scheduler prepares tomorrow's output address before the first entry is written. Converting that name into an absolute path should not create the missing report as a side effect.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
File draft = new File(desk.toFile(), "tomorrow.csv");
System.out.println(draft.getAbsoluteFile().isAbsolute());
System.out.println(draft.exists());
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true false
The absolute File identifies an address while the future report is still absent.
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
Canonicalization can perform I/O and throw IOException. An absolute path can still contain redundant components.