← Back to Java series
πŸ’Ύ
Exceptions & I/O
Exceptions & I/O Β· Prerequisite: previous lecture

16. File I/O and NIO.2

Read and write files with the modern NIO.2 API (`java.nio.file.*`). Covers `Path`, `Files.readString` / `writeString`, line-based reads, and the difference with the legacy `java.io.File`.

Javafile I/ONIO.2PathFiles
Duration
⏱ ~1.5-2 hours
Level
πŸ“Š Intermediate
Prerequisite
🎯 Previous lecture or equivalent knowledge
OUTCOME
Read and write files with the modern NIO.2 API (`java.nio.file.*`). Covers `Path`, `Files.readString` / `writeString`, line-based reads, and the difference with the legacy `java.io.File`.

What you'll learn

  • 1Build paths with `Path` and `Paths`
  • 2Read/write text with `Files.readString` / `writeString`
  • 3Stream lines with `Files.lines`
  • 4Compare with the legacy `java.io.File` API

Overview

Read and write files with the modern NIO.2 API (`java.nio.file.*`). Covers `Path`, `Files.readString` / `writeString`, line-based reads, and the difference with the legacy `java.io.File`.

Core Concepts

1) `Path` and `Paths`

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

Path p1 = Path.of("data", "users.txt");        // relative
Path p2 = Paths.get("/tmp/log.txt");            // absolute
System.out.println(p1.getFileName());           // users.txt
System.out.println(p1.toAbsolutePath());

2) `Files.writeString` / `readString` (JDK 11+)

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

Files.writeString(Path.of("out.txt"), "hello\nworld\n");
String text = Files.readString(Path.of("out.txt"));
System.out.println(text);

3) Line-based reads

java
import java.util.List;
import java.util.stream.Stream;

List<String> all = Files.readAllLines(Path.of("out.txt"));
try (Stream<String> lines = Files.lines(Path.of("out.txt"))) {
    lines.forEach(System.out::println);
}

`Files.lines` returns a lazy `Stream` β€” wrap in try-with-resources.

4) Append mode

java
import java.nio.file.StandardOpenOption;
Files.writeString(Path.of("log.txt"), "more\n", StandardOpenOption.APPEND);

5) Binary I/O

java
byte[] data = Files.readAllBytes(Path.of("photo.png"));
Files.write(Path.of("copy.png"), data);

Examples

Example 1 β€” `WriteRead.java`

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

public class WriteRead {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("hello.txt");
        Files.writeString(p, "Hello, NIO.2!\n");
        String s = Files.readString(p);
        System.out.print(s);
    }
}

**Output**

text
Hello, NIO.2!

Example 2 β€” `ReadLines.java`

java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class ReadLines {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("data.txt");
        Files.writeString(p, "alpha\nbeta\ngamma\n");

        List<String> lines = Files.readAllLines(p);
        for (int i = 0; i < lines.size(); i++) {
            System.out.println((i + 1) + ": " + lines.get(i));
        }
    }
}

**Output**

text
1: alpha
2: beta
3: gamma

Example 3 β€” `StreamLines.java`

java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

public class StreamLines {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("big.txt");
        Files.writeString(p, "a\nbb\nccc\ndddd\n");

        try (Stream<String> lines = Files.lines(p)) {
            long longLines = lines.filter(s -> s.length() >= 3).count();
            System.out.println("long lines = " + longLines);
        }
    }
}

**Output**

text
long lines = 2

Example 4 β€” `Append.java`

java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class Append {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("log.txt");
        Files.writeString(p, "first\n");
        Files.writeString(p, "second\n", StandardOpenOption.APPEND);
        System.out.print(Files.readString(p));
    }
}

**Output**

text
first
second

Common Mistakes

  1. Forgetting that `Files.lines` returns a `Stream` and skipping try-with-resources
  2. Using `\n` on Windows and breaking line splitting
  3. Reading a huge file with `readAllLines` and OOM
  4. Mixing the legacy `java.io.File` API with NIO.2 paths
  5. Catching `IOException` and silently ignoring it

Summary

  • Prefer `Path` + `Files.*` over the legacy `File`
  • Wrap `Files.lines` in try-with-resources
  • Use `StandardOpenOption.APPEND` to append

Practice

# Practice - 16. File I/O

## Exercise 1 β€” Line count

  • File: `Homework01.java`
  • Key concepts: `Files.lines`, `count`

Requirements

  • Create `data.txt` with three lines, then count them with `Files.lines`.
  • Print `lines=3`.

Expected output

text
lines=3

## Exercise 2 β€” Append timestamped log

  • File: `Homework02.java`
  • Key concepts: `APPEND`, `Instant.now`

Requirements

  • Append three lines like `<timestamp> hello` to `app.log`.
  • Read back and print.

Expected output

text
2026-01-01T00:00:00Z hello
... (three lines)

## Solutions After trying it yourself, compare with [`answer/`](./answer/).

Solution code (homework/answer/)

answer/Homework01.java

java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

/** Line count. */
public class Homework01 {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("data.txt");
        Files.writeString(p, "line1\nline2\nline3\n");

        try (Stream<String> lines = Files.lines(p)) {
            System.out.println("lines=" + lines.count());
        }
    }
}

answer/Homework02.java

java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Instant;

/** Append timestamped log. */
public class Homework02 {
    public static void main(String[] args) throws IOException {
        Path log = Path.of("app.log");
        Files.writeString(log, "");
        for (int i = 0; i < 3; i++) {
            Files.writeString(log, Instant.now() + " hello\n", StandardOpenOption.APPEND);
        }
        System.out.print(Files.readString(log));
    }
}

Try It Yourself

bash
cd 04_io/16_file_io/src
javac WriteRead.java
java WriteRead

Next Lecture

[17_Strings_and_Text_Blocks](../17_λ¬Έμžμ—΄_ν…μŠ€νŠΈ_블둝/) β€” String, StringBuilder, text blocks, `String.format`.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—