NBKRIST JavaHub

Deep dive — NIO.2 (java.nio.file) with examples & diagram

Expert View — NIO.2
In enterprise development, NIO.2 became indispensable: it offers robust file operations, safer error reporting, and powerful directory traversal. I used Path/Files in production systems for log rotation, file-based configuration, and safe atomic moves. Learn NIO.2 early — it simplifies real-world tasks and makes systems more resilient.

Quick Intro

Java NIO.2 (introduced in Java 7) modernizes file handling with the java.nio.file API. Core types: Path — represents a path; Files — utility operations for reading/writing/copying/deleting; FileSystem — abstraction over the OS file system.

FileSystem represents the OS filesystem Examples: default FileSystem, ZIP FileSystem Path represents file/directory location Files utility operations (read/write/copy) creates/returns used by operates on Examples of Files methods readString, writeString, copy, move, deleteIfExists

1. Creating & Writing a File (NIO.2)

// Files.writeString(Path.of("example.txt"), "NBKRIST: NIO.2 sample");

import java.nio.file.*;
import java.io.IOException;

public class CreateFileNio {
  public static void main(String[] args) throws IOException {
    Path p = Path.of("example.txt");
    Files.writeString(p, "NBKRIST: NIO.2 sample");
    System.out.println("Created and wrote example.txt");
  }
}
  
👉 Hover to view output

2. Reading from a File


import java.nio.file.*;
import java.io.IOException;

public class ReadFileNio {
  public static void main(String[] args) throws IOException {
    Path p = Path.of("example.txt");
    String s = Files.readString(p);
    System.out.println("Content: " + s);
  }
}
  
👉 Hover to view output

3. Directory Traversal (DirectoryStream)

// DirectoryStream<Path> stream = Files.newDirectoryStream(Path.of("."));

import java.nio.file.*;
import java.io.IOException;

public class ListDirNio {
  public static void main(String[] args) throws IOException {
    try (DirectoryStream stream = Files.newDirectoryStream(Path.of("."))) {
      for (Path p : stream) System.out.println(p.getFileName());
    }
  }
}
  
👉 Hover to view output

4. Copy / Move / Atomic Operations


import java.nio.file.*;
import java.io.IOException;

public class CopyMoveNio {
  public static void main(String[] args) throws IOException {
    Path src = Path.of("example.txt");
    Path backup = Path.of("backup_example.txt");
    Files.copy(src, backup, StandardCopyOption.REPLACE_EXISTING);
    System.out.println("Copied to backup_example.txt");
  }
}
  
👉 Hover to view output
💡 Tip: NIO.2 operations provide better error messages and options (e.g., atomic move, replace existing) — prefer them in production code.

Why NIO.2 beats legacy java.io.File

Practice Questions

1. Which core types are used in NIO.2 for file operations?
2. How do you quickly read or write small text files?
3. How to ensure move/copy replaces the target atomically?

Key Takeaways