Path and Files (NIO.2)
- Java course
- Expert
- Lesson 17/46
- 5 min
Learn the NIO.2 Path and Files API.
Path and Paths
With NIO.2 file paths are represented as Path objects. Paths.get("data", "file.txt") joins the parts and returns a Path; the separator is chosen for the operating system.
From a Path you get many things: getNameCount gives the number of path elements, getFileName the last element, getParent the parent path. Unlike the old File class, a path is just an address; actual file operations go through the Files class. This separates the path from the operation.
The Files class
The Files class performs operations on a Path. Most methods are static: Files.exists(p) checks presence, Files.size(p) gives the size, Files.readAllBytes(p) returns the content as bytes.
Example: Files.exists(Paths.get("log.txt")) returns true if the file exists. Files.createFile(p) creates a new file. These methods can throw IOException, so a throws declaration or try-catch is needed. Path holds only the address; Files does the real disk work.
Practice Print the path element count
Create a Path with Paths.get("kayit", "veri.txt"). Print the getNameCount result with System.out.println.
Starter code
// Create a path with Paths.get
// Print with getNameCountSample solution
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathDemo {
public static void main(String[] args) {
Path p = Paths.get("kayit", "veri.txt");
System.out.println(p.getNameCount());
}
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Path concepts
| Term | Meaning |
|---|---|
Paths.get |
Builds a path |
Path |
Path abstraction |
getNameCount |
Element count |
getFileName |
Last element |
2 Complete the Paths.get call
Path p = Paths.____("kayit", "veri.txt");
Path p = Paths.get("kayit", "veri.txt");
Explanation: Paths.get joins path parts.
3 What does Paths.get(...) return?
- A String
- A Path Correct answer
- A Channel
- A ByteBuffer
Explanation: Paths.get returns a Path object.