Lab 06: File I/O & NIO.2

Objective

Master Java file operations using java.nio.file: Path, Files, Files.walk, Files.lines, BufferedReader/Writer, CSV read/write, directory trees, copy/move/delete, and file attributes.

Background

Java NIO.2 (java.nio.file) replaced the legacy java.io.File API in Java 7. Path is immutable and composable; Files provides static utilities that are cleaner and more powerful than File methods. Files.lines() returns a lazy Stream<String> — perfect for processing large files without loading them entirely into memory.

Time

25 minutes

Prerequisites

  • Lab 05 (Concurrency)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Steps 1–8: Write CSV, read with Files.lines, directory tree, BufferedWriter report, copy/move, attributes, Capstone

💡 Files.lines() returns a lazy stream — it reads the file line-by-line as you consume the stream, not all at once. Always wrap it in try-with-resources so the underlying file handle is closed when the stream terminates. For large log files or CSVs (millions of rows), this is the memory-efficient approach.

📸 Verified Output:


Summary

API
Purpose

Path.of("...") / Paths.get(...)

Create path object

Files.write(path, lines)

Write all lines

Files.readAllLines(path)

Read all lines into List<String>

Files.lines(path)

Lazy Stream<String>

Files.createDirectories(path)

Create dir tree

Files.walk(path)

Recursive directory stream

Files.copy(src, dst, options)

Copy file

Files.size(path)

File size in bytes

Further Reading

Last updated