NIO.2 File API in Java

Master java.nio.file API, Path interface, Files class, directory traversal, file creation, reading, writing, file properties, and NIO.2 features for the OCP 21 exam.

Table of Contents

1. NIO.2 Overview

NIO.2 (New I/O 2) was introduced in Java 7, providing improved file I/O operations through the java.nio.file package.

1.1 Key Classes

  • Path - Represents a file or directory path
  • Paths - Factory class for creating Path objects
  • Files - Utility class for file operations
  • FileSystem - File system abstraction

2. Path Interface

2.1 Creating Path Objects

Example:
import java.nio.file.Path;
import java.nio.file.Paths;

// Creating Path objects
Path path1 = Paths.get("file.txt");
Path path2 = Paths.get("/home/user/file.txt");
Path path3 = Paths.get("dir", "subdir", "file.txt");
Path path4 = Path.of("file.txt");  // Java 11+

// Path operations
Path absolute = path1.toAbsolutePath();
Path normalized = path1.normalize();
Path resolved = path1.resolve("other.txt");
Path parent = path1.getParent();
String fileName = path1.getFileName().toString();
int nameCount = path1.getNameCount();

3. Files Class

The Files class provides static methods for file operations.

3.1 Reading Files

Example:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

Path path = Paths.get("file.txt");

// Read all lines
List<String> lines = Files.readAllLines(path);

// Read all bytes
byte[] bytes = Files.readAllBytes(path);

// Read as stream
Files.lines(path).forEach(System.out::println);

// Read with charset
List<String> linesUTF8 = Files.readAllLines(path, StandardCharsets.UTF_8);

3.2 Writing Files

Example:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;

Path path = Paths.get("output.txt");

// Write lines
List<String> lines = Arrays.asList("Line 1", "Line 2");
Files.write(path, lines);

// Write bytes
byte[] data = "Hello".getBytes();
Files.write(path, data);

// Append to file
Files.write(path, "New line".getBytes(), StandardOpenOption.APPEND);

// Write with options
Files.write(path, lines, StandardOpenOption.CREATE, 
    StandardOpenOption.TRUNCATE_EXISTING);

4. Directory Operations

4.1 Creating and Traversing Directories

Example:
import java.nio.file.*;
import java.util.stream.Stream;

// Create directory
Path dir = Paths.get("mydir");
Files.createDirectory(dir);
Files.createDirectories(Paths.get("dir1/dir2/dir3"));  // Creates parent dirs

// List directory contents
try (Stream<Path> stream = Files.list(dir)) {
    stream.forEach(System.out::println);
}

// Walk directory tree
try (Stream<Path> stream = Files.walk(dir)) {
    stream.forEach(System.out::println);
}

// Find files
try (Stream<Path> stream = Files.find(dir, Integer.MAX_VALUE,
        (path, attrs) -> path.toString().endsWith(".txt"))) {
    stream.forEach(System.out::println);
}

5. File Operations

5.1 File Properties and Operations

Example:
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

Path path = Paths.get("file.txt");

// Check file properties
boolean exists = Files.exists(path);
boolean isDirectory = Files.isDirectory(path);
boolean isRegularFile = Files.isRegularFile(path);
boolean isReadable = Files.isReadable(path);
boolean isWritable = Files.isWritable(path);
long size = Files.size(path);

// Get file attributes
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
FileTime creationTime = attrs.creationTime();
FileTime lastModified = attrs.lastModifiedTime();

// Copy file
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

// Move file
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);

// Delete file
Files.delete(path);
Files.deleteIfExists(path);  // No exception if doesn't exist

6. Exam Key Points

Critical Concepts for OCP 21 Exam:

  • Path: Represents file or directory path
  • Paths.get(): Create Path object
  • Path.of(): Create Path (Java 11+)
  • Files.readAllLines(): Read all lines from file
  • Files.readAllBytes(): Read all bytes from file
  • Files.lines(): Read file as Stream
  • Files.write(): Write to file
  • Files.createDirectory(): Create single directory
  • Files.createDirectories(): Create directory hierarchy
  • Files.list(): List directory contents
  • Files.walk(): Walk directory tree
  • Files.find(): Find files matching predicate
  • Files.copy(): Copy file or directory
  • Files.move(): Move/rename file or directory
  • Files.delete(): Delete file or directory
  • StandardOpenOption: Options for file operations

Post a Comment

0 Comments