Module 19: File Handling & NIO.2Beginner22 min read
File Handling with File and Modern Files / Path (NIO.2)
Compare legacy java.io.File with modern java.nio.file.Path and Files APIs for safe, clean file and directory operations.
Key Takeaways & Core Concepts
- (missing file vs permission denied vs non-empty directory), and it lacks symbolic-link and atomic-move support.
- (
java.nio.file.PathandFiles, introduced in Java 7 and enhanced in Java 11) fixes all of this: Path.of("dir", "sub", "file.txt"): OS-independent path construction.Files.readString(path)/Files.writeString(path, text)(Java 11+): Clean one-line UTF-8 file I/O.
File Handling with File and Modern Files / Path (NIO.2)
### Legacy java.io.File vs Modern NIO.2 (Path & Files) Legacy java.io.File has major shortcomings: file.delete() returns false without explaining why (missing file vs permission denied vs non-empty directory), and it lacks symbolic-link and atomic-move support.
Modern NIO.2 (java.nio.file.Path and Files, introduced in Java 7 and enhanced in Java 11) fixes all of this:
Path.of("dir", "sub", "file.txt"): OS-independent path construction.Files.readString(path)/Files.writeString(path, text)(Java 11+): Clean one-line UTF-8 file I/O.Files.lines(path): Returns a lazyStream<String>so multi-gigabyte log files can be processed without loading the whole file into Heap RAM (always wrap intry (var lines = Files.lines(path))).
NIO.2 Path Resolution & Normalization
1import java.nio.file.Path;
2
3public class Main {
4 public static void main(String[] args) {
5 Path base = Path.of("workspace", "java-notes");
6 Path file = base.resolve("../java-notes/chapter1.md").normalize();
7 System.out.println("File Name: " + file.getFileName());
8 System.out.println("Normalized: " + file);
9 }
10}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
10 lines
Note: `normalize()` resolves `.` and `..` segments cleanly without hitting the filesystem.
Practice & AssessmentJava Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)