Java · Module 10 · Lesson 11 min read

Reading & Writing Files

The modern way: java.nio.file

Java
Path path = Path.of("data", "notes.txt");

Files.createDirectories(path.getParent());          // make folders
Files.writeString(path, "Hello file!\n");           // create / overwrite
Files.writeString(path, "More text\n",
                  StandardOpenOption.APPEND);       // add to the end

String all = Files.readString(path);                // whole file
List<String> lines = Files.readAllLines(path);      // one String per line
boolean exists = Files.exists(path);
Files.deleteIfExists(path);

All of these can throw the checked IOException, so handle or declare it.

Big files: read line by line 🐘

readAllLines loads everything into memory. For huge files, stream them:

Java
try (Stream<String> stream = Files.lines(path)) {
    long errors = stream.filter(l -> l.contains("ERROR")).count();
}

or use a BufferedReader:

Java
try (BufferedReader br = Files.newBufferedReader(path)) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}

⚠️ Always close streams and readers. try-with-resources does it for you.

Writing with BufferedWriter

Java
try (BufferedWriter bw = Files.newBufferedWriter(path)) {
    bw.write("Line 1");
    bw.newLine();
}

Character encoding

Since Java 18, the default charset is UTF-8 everywhere, so emojis and other languages save correctly. 🎉

Older classes you'll still see

File, FileReader, FileWriter, FileInputStream. They work, but the Files + Path API is simpler and safer.

Example

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

public class Journal {
    public static void main(String[] args) {
        Path file = Path.of("journal.txt");
        try {
            Files.writeString(file, "Day 1: Started Java ☕\n");
            Files.writeString(file, "Day 2: Learned files 📁\n",
                              StandardOpenOption.APPEND);

            List<String> entries = Files.readAllLines(file);
            System.out.println("Entries: " + entries.size());  // 2
            entries.forEach(System.out::println);
        } catch (IOException e) {
            System.out.println("File error: " + e.getMessage());
        }
    }
}