Java · Lesson 17 of 20

Files and I/O

Read and write files with java.nio and handle resources with try-with-resources.

  • Intermediate
  • 14 min read
  • 3 objectives

Before this lessonLesson 16: Dates and Times with java.time

What you will learn

  • Read and write text files
  • Use try-with-resources
  • Work with Path

Your Progress

0 of 20 lessons 0%

  • Lessons0 / 20
  • Completed0
  • Est. time left~ 5 hours

Progress is saved in this browser. No account needed.

Tip: pressing Next marks this lesson complete automatically.

Modern Java reads and writes files through java.nio.file: Path describes a location and Files does the work. Most methods throw IOException, which you must catch or declare.

Write and read a text file

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("notes.txt");
        Files.writeString(file, "first\nsecond\nthird\n");
        List<String> lines = Files.readAllLines(file);
        System.out.println(lines.size() + " lines");
        System.out.println(lines.get(1));
        Files.delete(file);
    }
}
Output
3 lines
second

Big files: stream lines

readAllLines loads everything into memory. For large files read line by line with a BufferedReader.

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        try (BufferedReader in = new BufferedReader(new FileReader("data.txt"))) {
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

try-with-resources

Anything that implements AutoCloseable declared in the try (...) parentheses is closed automatically, even if an exception is thrown. It replaces a manual finally block.

Working with paths

import java.nio.file.*;

public class Main {
    public static void main(String[] args) {
        Path p = Path.of("data", "2025", "report.csv");
        System.out.println(p);
        System.out.println(p.getFileName());
        System.out.println(p.getParent());
        System.out.println(Files.exists(p));
    }
}
Output
data/2025/report.csv
report.csv
data/2025
false

Finished reading? Mark this lesson complete to track your progress.

Up next · Lesson 18Threads, Executors and CompletableFutureLearn Java concurrency: threads, race conditions, synchronized and atomics, ExecutorService, CompletableFuture pipelines and Java 21 virtual threads.