SyntaxPilot
Courses/Java/Lesson 35
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Java · Lesson 35 of 51

File I/O and NIO

queued

These are the notes for Java episode 35. Ravi's chai-stall program counts how many days he has opened the shop, but every run says "Visit number 1": the count lives in a variable, and variables live in RAM, which is wiped when the program ends. We invent files (data on the disk that survives), meet the checked IOException, learn why a second write wipes the first and how APPEND fixes it, recover from NoSuchFileException, read records from a CSV file, discover why a forgotten close() leaves an empty file, read a million-line log with a BufferedReader, and create folders. Every example was run with javac 21.

The problem: programs forget

public class Main {
    static int visits = 0;

    public static void main(String[] args) {
        visits++;
        System.out.println("Welcome to Ravi's Chai Stall!");
        System.out.println("Visit number " + visits);
    }
}

Output, on every single run:

Welcome to Ravi's Chai Stall!
Visit number 1

A static variable lives as long as the program runs, not one second longer. Run it tomorrow and visits starts at 0 again.

Real-life example: whiteboard vs notebook.

In the shop In a computer Meaning
Whiteboard, wiped every night RAM (memory) fast, but temporary: variables, objects, lists
Notebook register in the drawer Disk (storage: SSD / hard disk) slower, but survives the program ending and a restart
A named page in the notebook File a name plus bytes stored on the disk

Reading and writing files is called file I/O (input/output).

Path and Files (java.nio.file)

Java's modern file API (Java 7+, "NIO.2") lives in java.nio.file:

  • Path: the address of a file or folder, e.g. Path.of("diary.txt") or Path.of("shop", "2026", "nov.txt"). A Path is just a name; creating one does not create a file.
  • Files: a class full of static methods that do the actual work: writeString, readString, write, readAllLines, exists, size, createDirectories, newBufferedReader, newBufferedWriter, ...

A relative path like diary.txt is resolved against the program's working directory (the folder it runs in). An absolute path starts from the root, e.g. /home/ravi/diary.txt or C:\Users\Ravi\diary.txt.

Writing a file: IOException is checked

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

public class Main {
    public static void main(String[] args) {
        Path diary = Path.of("diary.txt");
        Files.writeString(diary, "Sold 40 cups of chai\n");
        System.out.println("Saved!");
    }
}
Main.java:7: error: unreported exception IOException; must be caught or declared to be thrown
        Files.writeString(diary, "Sold 40 cups of chai\n");
                         ^
1 error

Writing can fail for reasons outside your program: the disk is full, the file is locked, you have no permission. IOException is a checked exception (episode 26), so the compiler forces you to either catch it or declare it with throws.

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path diary = Path.of("diary.txt");
        Files.writeString(diary, "Sold 40 cups of chai\n");
        System.out.println("Saved! Exists? " + Files.exists(diary));
        System.out.println("Size: " + Files.size(diary) + " bytes");
        String text = Files.readString(diary);
        System.out.print("Read back: " + text);
    }
}
Saved! Exists? true
Size: 21 bytes
Read back: Sold 40 cups of chai

"Sold 40 cups of chai" is 20 characters plus the newline \n = 21 bytes (plain English text uses one byte per character in UTF-8, the default encoding).

Overwrite vs append

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path diary = Path.of("diary.txt");
        Files.writeString(diary, "Monday: 40 cups\n");
        Files.writeString(diary, "Tuesday: 55 cups\n");
        System.out.print(Files.readString(diary));
    }
}
Tuesday: 55 cups

By default writeString creates the file if it is missing and truncates it (empties it) if it exists. Monday is gone. To add to the end, pass open options:

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path diary = Path.of("diary.txt");
        Files.writeString(diary, "Monday: 40 cups\n");
        Files.writeString(diary, "Tuesday: 55 cups\n",
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        Files.writeString(diary, "Wednesday: 38 cups\n",
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        System.out.print(Files.readString(diary));
    }
}
Monday: 40 cups
Tuesday: 55 cups
Wednesday: 38 cups
Option Meaning
(none) CREATE, TRUNCATE_EXISTING, WRITE: replace the file
APPEND write at the end; fails with NoSuchFileException if the file is missing
CREATE, APPEND create if missing, otherwise add at the end: the combination for logs and diaries
CREATE_NEW create, but fail with FileAlreadyExistsException if it exists

Missing files: NoSuchFileException

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

public class Main {
    public static void main(String[] args) throws IOException {
        Files.writeString(Path.of("diary.txt"), "Monday: 40 cups\n");
        String text = Files.readString(Path.of("dairy.txt"));
        System.out.print(text);
    }
}
Exception in thread "main" java.nio.file.NoSuchFileException: dairy.txt
    ...
    at Main.main(Main.java:8)

A typo (dairy instead of diary) compiles fine, because throws IOException only says something might fail. At run time it does. But a missing file is not always a bug: on the very first run, the register does not exist yet. Catch the specific exception first, then the general one:

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

public class Main {
    public static void main(String[] args) {
        Path p = Path.of("dairy.txt");
        try {
            System.out.print(Files.readString(p));
        } catch (NoSuchFileException e) {
            System.out.println("No file " + e.getMessage()
                    + " yet. Starting fresh.");
        } catch (IOException e) {
            System.out.println("Could not read: " + e.getMessage());
        }
    }
}
No file dairy.txt yet. Starting fresh.

NoSuchFileException is a subclass of IOException, so it must be caught before IOException (otherwise: error: exception NoSuchFileException has already been caught). You can also check first with Files.exists(path).

The counter finally remembers

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

public class Main {
    static void openShop() throws IOException {
        Path file = Path.of("visits.txt");
        int visits = 0;
        if (Files.exists(file)) {
            visits = Integer.parseInt(Files.readString(file).trim());
        }
        visits++;
        Files.writeString(file, String.valueOf(visits));
        System.out.println("Visit number " + visits);
    }

    public static void main(String[] args) throws IOException {
        openShop();   // day 1
        openShop();   // day 2
        openShop();   // day 3
    }
}
Visit number 1
Visit number 2
Visit number 3

Each call starts with visits = 0; the real count comes from the file. (The SyntaxPilot online compiler gives every run a fresh, empty folder, so the video calls openShop() three times in one run. On your own computer, run it three times and you get 1, 2, 3.)

Many records: CSV with readAllLines

CSV (comma-separated values) is plain text with one record per line and fields separated by commas. Spreadsheets open it directly.

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("marks.csv");
        Files.write(file, List.of("Ravi,72", "Asha,95", "Meena,64", "Kabir,88"));

        List<String> lines = Files.readAllLines(file);
        int total = 0;
        for (String line : lines) {
            String[] parts = line.split(",");
            String name = parts[0];
            int marks = Integer.parseInt(parts[1]);
            System.out.println(name + " scored " + marks);
            total += marks;
        }
        System.out.println("Class average: " + (double) total / lines.size());
    }
}
Ravi scored 72
Asha scored 95
Meena scored 64
Kabir scored 88
Class average: 79.75
  • Files.write(path, list) writes each String as one line.
  • Files.readAllLines(path) returns a List<String>, one element per line.
  • A file stores text: split(",") cuts a line into fields and Integer.parseInt turns "72" back into the number 72.

Big files: buffers and close()

Real-life example: a bucket vs a tap.

At home In Java Meaning
Fill a bucket readAllLines / readString the whole file in memory at once: fine for small files
Open a tap BufferedReader.readLine() one line at a time: memory stays tiny for any file size
A tank before the pipe Buffer collects bytes in memory and moves them in big chunks: fewer slow disk trips

A buffer is a block of memory that collects data so the disk is touched rarely. The catch: data waits in the buffer until it is full, flushed (flush()), or closed (close()).

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path bill = Path.of("bill.txt");
        BufferedWriter out = Files.newBufferedWriter(bill);
        out.write("Chai x2 = 30\n");
        out.write("Samosa x1 = 15\n");
        // forgot out.close()
        System.out.println("On disk: " + Files.size(bill) + " bytes");
    }
}
On disk: 0 bytes

The two lines are still in the buffer. The fix is try-with-resources (episode 27): anything opened inside try ( ... ) is closed automatically at the closing brace, even if an exception is thrown.

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path bill = Path.of("bill.txt");
        try (BufferedWriter out = Files.newBufferedWriter(bill)) {
            out.write("Chai x2 = 30\n");
            out.write("Samosa x1 = 15\n");
        }   // close() runs here, automatically
        System.out.println("On disk: " + Files.size(bill) + " bytes");
        System.out.print(Files.readString(bill));
    }
}
On disk: 28 bytes
Chai x2 = 30
Samosa x1 = 15

A million lines, one at a time

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path log = Path.of("orders.log");
        try (BufferedWriter out = Files.newBufferedWriter(log)) {
            for (int i = 1; i <= 1_000_000; i++) {
                out.write("order" + i + "," + (i % 3 == 0 ? 15 : 10) + "\n");
            }
        }
        System.out.println("File size: " + Files.size(log) / 1_000_000 + " MB");

        long count = 0, rupees = 0;
        try (BufferedReader in = Files.newBufferedReader(log)) {
            String line;
            while ((line = in.readLine()) != null) {
                count++;
                rupees += Integer.parseInt(line.split(",")[1]);
            }
        }
        System.out.println(count + " orders, Rs " + rupees);
    }
}
File size: 14 MB
1000000 orders, Rs 11666665

readLine() returns the next line without its newline, and null at the end of the file. At any moment only one line is in memory.

Folders and paths

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("shop", "2026", "nov.txt");
        Files.writeString(file, "November sales\n");
    }
}
Exception in thread "main" java.nio.file.NoSuchFileException: shop/2026/nov.txt
    ...
    at Main.main(Main.java:8)

writeString never creates folders. Files.createDirectories creates every missing folder on the way (like mkdir -p) and does nothing if they already exist:

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("shop", "2026", "nov.txt");
        System.out.println("Name:   " + file.getFileName());
        System.out.println("Folder: " + file.getParent());
        Files.createDirectories(file.getParent());
        Files.writeString(file, "November sales\n");
        Files.writeString(file.resolveSibling("dec.txt"), "December sales\n");

        Path month = file.getParent();
        try (DirectoryStream<Path> folder = Files.newDirectoryStream(month)) {
            for (Path p : folder) System.out.println("Found:  " + p);
        }
    }
}
Name:   nov.txt
Folder: shop/2026
Found:  shop/2026/dec.txt
Found:  shop/2026/nov.txt
Method Result for shop/2026/nov.txt
getFileName() nov.txt
getParent() shop/2026
resolveSibling("dec.txt") shop/2026/dec.txt
resolve("x.txt") (on the folder) shop/2026/x.txt
toAbsolutePath() the full path from the root

A DirectoryStream lists a folder's entries; the order is not guaranteed, so sort if order matters. Other useful methods: Files.copy, Files.move, Files.delete, Files.deleteIfExists, Files.isDirectory.

The old way: java.io

Code written before Java 7 (and plenty written after) uses java.io:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
        File f = new File("old.txt");
        try (FileWriter w = new FileWriter(f, true)) {   // true = append
            w.write("written the old way\n");
        }
        System.out.println(f.exists() + " " + f.length() + " bytes");
        try (Scanner sc = new Scanner(f)) {
            while (sc.hasNextLine()) System.out.println(sc.nextLine());
        }
    }
}
true 20 bytes
written the old way
java.io (old) java.nio.file (modern)
new File("a.txt") Path.of("a.txt")
new FileWriter(f, true) (append) Files.writeString(p, s, CREATE, APPEND)
new FileReader(f) / new Scanner(f) Files.readString(p) / Files.readAllLines(p)
new BufferedReader(new FileReader(f)) Files.newBufferedReader(p)
f.exists(), f.length() Files.exists(p), Files.size(p)
f.mkdirs() returns false on failure Files.createDirectories(p) throws a clear exception

Convert between them with file.toPath() and path.toFile(). Prefer Path + Files in new code: clearer methods and clearer errors.

Common mistakes (and the real error messages)

Mistake What you see Why Fix
Files.writeString(p, s) with no throws/catch error: unreported exception IOException; must be caught or declared to be thrown file work is a checked exception throws IOException or try/catch
writeString twice on one file no error; only the last text is left the default write truncates StandardOpenOption.CREATE, StandardOpenOption.APPEND
Reading dairy.txt instead of diary.txt java.nio.file.NoSuchFileException: dairy.txt wrong name, or first run check Files.exists or catch NoSuchFileException
BufferedWriter never closed no error; On disk: 0 bytes the buffer was never flushed try-with-resources
Writing into shop/2026/nov.txt java.nio.file.NoSuchFileException: shop/2026/nov.txt the folders don't exist Files.createDirectories(path.getParent())
catch (IOException e) before catch (NoSuchFileException e) error: exception NoSuchFileException has already been caught the general catch already covers it specific exceptions first
readAllLines on a multi-GB file OutOfMemoryError: Java heap space the whole file in memory BufferedReader.readLine()

Mini project: the sales register

Every sale is appended to sales.csv; a report reads it back and also writes a summary file.

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

public class Main {
    static final Path SALES = Path.of("sales.csv");

    static void record(String item, int qty, int price) throws IOException {
        String line = item + "," + qty + "," + price + "\n";
        Files.writeString(SALES, line, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    }

    static void report() throws IOException {
        if (!Files.exists(SALES)) { System.out.println("No sales yet."); return; }
        List<String> lines = Files.readAllLines(SALES);
        int total = 0;
        for (String line : lines) {
            String[] p = line.split(",");
            int amount = Integer.parseInt(p[1]) * Integer.parseInt(p[2]);
            System.out.printf("%-8s x%d = Rs %d%n", p[0], Integer.parseInt(p[1]), amount);
            total += amount;
        }
        System.out.println("Total: Rs " + total);
        try (BufferedWriter out = Files.newBufferedWriter(Path.of("report.txt"))) {
            out.write("Orders: " + lines.size() + ", total Rs " + total + "\n");
        }
        System.out.print("report.txt says: " + Files.readString(Path.of("report.txt")));
    }

    public static void main(String[] args) throws IOException {
        report();
        record("chai", 40, 15);
        record("samosa", 25, 12);
        record("chai", 12, 15);
        report();
    }
}
No sales yet.
chai     x40 = Rs 600
samosa   x25 = Rs 300
chai     x12 = Rs 180
Total: Rs 1080
report.txt says: Orders: 3, total Rs 1080

Practice

  1. A to-do app that appends tasks to todo.txt and prints them numbered.
  2. Count the words in a text file (lines can be empty or contain extra spaces).
  3. Copy a file line by line, numbering each line, using a BufferedReader and a BufferedWriter.
  4. Save a list of students to a CSV file, read it back and print the topper.
Solution 1: to-do app
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;

public class Main {
    static final Path TODO = Path.of("todo.txt");

    static void add(String task) throws IOException {
        Files.writeString(TODO, task + "\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    }

    static void show() throws IOException {
        List<String> tasks = Files.exists(TODO) ? Files.readAllLines(TODO) : List.of();
        for (int i = 0; i < tasks.size(); i++) System.out.println((i + 1) + ". " + tasks.get(i));
    }

    public static void main(String[] args) throws IOException {
        add("buy milk");
        add("pay electricity bill");
        add("revise episode 35");
        show();
    }
}
1. buy milk
2. pay electricity bill
3. revise episode 35
Solution 2: word counter
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("story.txt");
        Files.writeString(p, "Ravi opened the stall.\nThe chai was hot,\n\nand the rain   was heavy.\n");
        int words = 0;
        for (String line : Files.readAllLines(p)) {
            String t = line.trim();
            if (!t.isEmpty()) words += t.split("\\s+").length;
        }
        System.out.println("Words: " + words);
    }
}
Words: 13

split("\\s+") splits on one or more whitespace characters; blank lines are skipped.

Solution 3: numbered copy
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path src = Path.of("poem.txt"), dst = Path.of("poem_numbered.txt");
        Files.writeString(src, "Chai in the morning\nChai at noon\nChai at night\n");
        try (BufferedReader in = Files.newBufferedReader(src);
             BufferedWriter out = Files.newBufferedWriter(dst)) {
            String line; int n = 0;
            while ((line = in.readLine()) != null) {
                out.write(++n + ": " + line);
                out.newLine();
            }
        }
        System.out.print(Files.readString(dst));
    }
}
1: Chai in the morning
2: Chai at noon
3: Chai at night

Two resources in one try ( ... ; ... ): both are closed, in reverse order.

Solution 4: students CSV and the topper
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

record Student(String name, int marks) {}

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("students.csv");
        List<Student> cls = List.of(new Student("Ravi", 72), new Student("Asha", 95), new Student("Meena", 64));
        List<String> lines = new ArrayList<>();
        for (Student s : cls) lines.add(s.name() + "," + s.marks());
        Files.write(file, lines);

        Student top = null;
        for (String line : Files.readAllLines(file)) {
            String[] p = line.split(",");
            Student s = new Student(p[0], Integer.parseInt(p[1]));
            if (top == null || s.marks() > top.marks()) top = s;
        }
        System.out.println("Topper: " + top.name() + " with " + top.marks());
    }
}
Topper: Asha with 95

Quick quiz

Path p = Path.of("q.txt");
Files.writeString(p, "A\n");
Files.writeString(p, "B\n", StandardOpenOption.APPEND);
Files.writeString(p, "C\n");
System.out.println(Files.readAllLines(p).size());

A) 3 B) 2 C) 1 D) It throws NoSuchFileException

Answer

C. After A and the appended B the file has 2 lines, but the third write has no APPEND, so it truncates the file and leaves only C.

1

Interview questions

  1. What is the difference between java.io.File and java.nio.file.Path? File is the old (Java 1.0) class that both names a file and does some operations, often returning false on failure. Path (Java 7) only represents the location; the Files class does the operations and throws descriptive exceptions.
  2. Why is IOException a checked exception? I/O depends on things outside the program (disk, permissions, network drives) that can fail at any time, so Java forces callers to handle or declare it.
  3. What does a buffer do, and why must you close a writer? It collects data in memory and writes it in large chunks to reduce slow system calls. Data still in the buffer is lost unless it is flushed; close() flushes and then releases the file handle.
  4. What is try-with-resources? try (Resource r = ...) { } closes every resource that implements AutoCloseable automatically, in reverse order, even if an exception is thrown.
  5. readAllLines vs BufferedReader? readAllLines loads the whole file into a List<String> (simple, for small files); BufferedReader.readLine() streams one line at a time (constant memory, for large files).
  6. How do you append to a file? Files.writeString(p, s, StandardOpenOption.CREATE, StandardOpenOption.APPEND) or new FileWriter(file, true).
  7. What happens if you don't close files at all? Unflushed data is lost and the operating system's file handles leak; a long-running program can fail with "Too many open files".
  8. What is the default character encoding of Files.readString/writeString? UTF-8.

Glossary

Term Meaning Example
RAM (memory) Fast, temporary storage; wiped when the program ends variables, objects
Disk (storage) Slower, permanent storage that survives restarts SSD, hard disk
File A name plus bytes stored on the disk diary.txt
File I/O Reading (input) and writing (output) files readString, writeString
Path The address of a file or folder Path.of("shop", "nov.txt")
Files Class of static methods that work on paths Files.exists(p)
Relative path Resolved against the working directory diary.txt
Absolute path Starts from the root of the file system /home/ravi/diary.txt
Working directory The folder the program runs in where diary.txt is created
IOException Checked exception for failed I/O disk full, no permission
Checked exception Must be caught or declared with throws IOException
Truncate Empty a file before writing default writeString
StandardOpenOption Flags that control how a file is opened CREATE, APPEND
Append Write at the end, keeping old content a log file
NoSuchFileException The file or folder does not exist dairy.txt
CSV Comma-separated values: one record per line Ravi,72
Parse Turn text into a value Integer.parseInt("72")
Buffer Memory that collects data to move it in chunks BufferedWriter
Flush Push buffered data to the disk now out.flush()
close() Flush and release the file end of try-with-resources
try-with-resources try ( ... ) that closes resources automatically try (BufferedWriter out = ...)
BufferedReader Reads text efficiently, line by line readLine()
readLine() Next line without \n, null at end of file while ((line = in.readLine()) != null)
BufferedWriter Writes text efficiently through a buffer out.write(...)
createDirectories Creates all missing folders in a path like mkdir -p
DirectoryStream Lists the entries of a folder Files.newDirectoryStream(dir)
java.io The original I/O package File, FileWriter, FileReader
java.nio.file The modern file API (Java 7+) Path, Files
UTF-8 The default text encoding; 1 byte per English letter "chai" = 4 bytes

Summary

  • Variables live in RAM and vanish when the program ends; files on the disk survive.
  • Path is the address, Files does the work: writeString, readString, write, readAllLines, exists, size.
  • IOException is checked: declare it with throws or catch it; catch NoSuchFileException first.
  • The default write replaces the file; CREATE, APPEND adds to it.
  • Small files: readAllLines; big files: BufferedReader.readLine() until null.
  • Buffers must be flushed: open every reader/writer in try-with-resources.
  • writeString never creates folders: Files.createDirectories(path.getParent()).
  • Old code uses java.io (File, FileWriter, Scanner); new code should use Path + Files.
  • Next: a whole class just to pass one rule? Lambdas and method references (episode 36).