Java Represent a Path Before Opening a File
A Path represents a filesystem location; it does not guarantee the file exists or is safe to access. Keep path construction distinct from actual I/O.
Understand the idea
Path.of builds a path using the host filesystem’s rules. resolve combines a base with a child, while normalize removes some syntactic redundancy. None of these operations alone establishes that an untrusted path stays within an allowed directory after symlinks and filesystem state are considered. For these lessons, create a fresh temporary directory so examples cannot overwrite a learner’s existing documents.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
Path folder = Files.createTempDirectory("bhylu-path-");
try {
Path file = folder.resolve("attendance.txt");
System.out.println(file.getFileName());
System.out.println(Files.exists(file));
} finally {
Files.delete(folder);
}
}
}
Expected output
attendance.txt
falseConstructing file does not create it. Its filename is available even though the location is absent. The fresh directory belongs to this example and is deleted after use. On another operating system, separators and roots can differ, so avoid hardcoding a Windows-only absolute path into a supposedly portable example.
Check the official Java documentation for detailed contracts and supported options.