Java Path.of and resolve
Path.of creates a path and resolve joins a relative child to a directory. You can build and inspect a receipt path before any file exists.
A simple example
Path.of and resolve
- Start with Directory notes and name a.txt
- Do this Join the two path components
- Result notes/a.txt on Unix
Syntax
Path.of("receipts").resolve("monday.txt")
JDK 21 declarations (6)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaFind Monday’s receipt
An office keeps individual receipts inside one archive. Work with the archive and its named entries so a clerk can locate the intended receipt without treating the archive itself as a single receipt.
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
Path folder = Path.of("receipts");
Path receipt = folder.resolve("monday.txt");
System.out.println(receipt.getParent().getFileName());
System.out.println(receipt.getFileName());
}
}
receipts monday.txt
The parent is the receipts directory and the final component is monday.txt. Printing the two names separately gives the same output on Windows, macOS, and Linux.
Assemble a student's submission path
A learning portal stores each class in its own folder. Given the class folder and a submitted filename, the receipt should show the student's filename even before the upload is saved.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path course = Path.of("classes", "biology");
Path upload = course.resolve("field-notes.txt");
System.out.println(upload.getFileName());
}
}
field-notes.txt
The resolved path describes a destination. Constructing it does not create the file.
Put a marked copy beside the original
A tutor needs to return feedback beside an assignment. The source folder can vary between courses, so the marking tool replaces only the last part of the submitted path.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path paper = Path.of("classes", "biology", "essay.txt");
Path marked = paper.resolveSibling("essay-marked.txt");
System.out.println(marked.getParent().equals(paper.getParent()));
System.out.println(marked.getFileName());
}
}
true essay-marked.txt
The parent stays the same while the filename changes.
What to watch for
An absolute child path takes precedence over the parent. Use a known relative filename when building a child path.