Path
- Java course
- Advanced
- Lesson 67/82
- 5 min
Learn the modern path object with Path.
Path
Path represents a file path in the java.nio.file package. It is created with Path.of("a/b.txt"); methods like getFileName() and getParent() give parts of the path.
import java.nio.file.Path;
Path p = Path.of("docs", "read.txt");
System.out.println(p.getFileName());
// read.txtUnlike the old java.io.File class, Path handles symbolic links and relative paths consistently. To operate on the path, the Files class is used. This separation is the core design of NIO.2.
Path parts
A Path's getFileName() gives the final file name, getParent() gives the parent directory, getRoot() gives the root. toAbsolutePath() converts to a full path.
Path p = Path.of("/home/alex/read.txt");
p.getFileName(); // read.txt
p.getParent(); // /home/alex
p.getRoot(); // /Although separators differ by operating system, Java uses /; it also works on Windows. resolve and relativize let you join paths and compute relative paths. This makes writing portable code easier.
Practice Print Path parts
Write main in a PathDemo class; create a Path with Path.of("docs", "read.txt"). Print the file name with System.out.println(p.getFileName()). Import the Path class with import java.nio.file.Path.
Starter code
import java.nio.file.Path;
// Write main in PathDemo
// Create a Path "docs/read.txt" with Path.of and print getFileNameSample solution
import java.nio.file.Path;
class PathDemo {
public static void main(String[] args) {
Path p = Path.of("docs", "read.txt");
System.out.println(p.getFileName());
}
}Expected output
read.txt
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Path.of(...) return?
- A File object
- A String
- A Path object Correct answer
- An InputStream
Explanation: Path.of(...) returns a Path object.
2 Complete the Path creation
import java.nio.file.Path;
Path p = ____("docs", "oku.txt");
import java.nio.file.Path;
Path p = Path.of("docs", "oku.txt");
Explanation: Path.of(...) is the modern Path creation method.
3 Match Path methods
| Term | Meaning |
|---|---|
getFileName |
Final file name |
getParent |
Parent directory |
toAbsolutePath |
Full path |
resolve |
Joins paths |