Files & Paths

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • The java.nio.file package (NIO.2) introduced the Path interface and the Files utility class.
  • They completely replace the legacy java.io.File class.
  • They provide simple, powerful, one-liner methods for copying, moving, reading, and writing files without dealing with Streams directly.

Concept

Before Java 7, developers used java.io.File. It was heavily flawed:

  • It lacked support for symbolic links.
  • If file.delete() failed, it returned false instead of throwing a useful Exception telling you why (e.g., Access Denied).
  • Reading a whole text file required 15 lines of BufferedReader code.

NIO.2 fixed this by separating the concept of a file location (Path) from the operations performed on it (Files). The Files class contains dozens of static methods that handle all the stream opening, buffering, and closing for you automatically.

Examples

import java.nio.file.*;
import java.util.List;

public class FilesDemo {
    public static void main(String[] args) throws Exception {
        
        // 1. Define a Path (The modern way to define a file location)
        Path path = Paths.get("data", "users", "emails.txt"); // data/users/emails.txt
        
        // 2. Write text to a file in a single line!
        String data = "user@example.com\nadmin@test.com";
        Files.writeString(path, data); // (Java 11+)
        
        // 3. Read all lines into a List in a single line!
        List<String> lines = Files.readAllLines(path);
        lines.forEach(System.out::println);
        
        // 4. Copy a file
        Path backup = Paths.get("emails_backup.txt");
        Files.copy(path, backup, StandardCopyOption.REPLACE_EXISTING);
        
        // 5. Delete a file
        Files.delete(backup); // Throws NoSuchFileException or AccessDeniedException!
    }
}

Interview Questions

Q: Why shouldn’t you use java.io.File anymore?
A: java.io.File is considered legacy. It has terrible error handling (returning booleans instead of exceptions), no concept of modern OS features like symlinks, and lacks metadata support (like reading POSIX file permissions). The java.nio.file.Path API solves all these issues and integrates perfectly with the modern Files utility methods. If you have legacy code returning a File, you can easily bridge it using file.toPath().

Q: How do you recursively walk a directory tree to find all .log files?
A: In the old days, you had to write a complex recursive method using file.listFiles(). In NIO.2, you use Files.walk(), which returns a modern Java Stream of Paths!

Files.walk(Paths.get("/var/logs"))
     .filter(Files::isRegularFile)
     .filter(p -> p.toString().endsWith(".log"))
     .forEach(System.out::println);