Lesson 5 of 618 minModule progress 0%

Module 10: Strings, Files, and Everyday Core APIs

Files and Paths with NIO.2

Work with Path and Files APIs to read, write, and inspect files in modern Java.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-17

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, manually edited for clarity, and checked against current Java documentation and runnable examples.

Learning goals

  • Use `Path` instead of raw string paths
  • Read and write files with the `Files` utility class
  • Handle missing files and file metadata more cleanly

Modern file code starts with Path: It represents a filesystem location in a safer, clearer way than passing raw strings everywhere.

The Files utility class handles common work: Reading text, writing text, checking existence, and creating directories all live there.

This is where exception handling becomes real: File operations often fail because the file is missing, locked, or the path is wrong.

Practical rule: Keep path creation, file IO, and validation close together so failures are easier to trace.

Runnable examples

Write and read a text file

import java.nio.file.Files;
import java.nio.file.Path;

Path file = Path.of("notes.txt");
Files.writeString(file, "Java 25\n");
System.out.println(Files.readString(file));

Expected output

Java 25

Mini exercise

Create a `Path` for `tasks.txt`, write one line to it, then read the content back.

Summary

  • `Path` and `Files` are the modern core APIs for file work.
  • IO code should expect failures and handle them clearly.
  • Keep file paths as structured values, not magic strings everywhere.

Next step

The module ends with a small log-file project that combines string work, formatting, regex, and files.

Sources used

Advertisement

Lesson check

Which type represents a file location in modern Java IO?

Next lesson →