Java + Spring Boot track

Lesson 16 · Part 4: Exceptions & I/O

File I/O

Reading and writing files is a function that almost every program needs. Focusing on Files and Path of Java's new IO API, java.nio.file, you will learn the…

Part 4: Exceptions & I/O3 min readFree lesson

Reading and writing files is a function that almost every program needs. Focusing on Files and Path of Java's new IO API, java.nio.file, you will learn the try-with-resources pattern to prevent resource leaks.

Learning Objectives

  • Know the role of Path and Files
  • Read and write text files with Files.readAllLines / Files.writeString
  • Know how to use BufferedReader and try-with-resources
  • Understand that IOException is a checked exception.

Key concepts

1) Path and Files

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

Path p = Path.of("data.txt");
Files.writeString(p, "Hello\nWorld\n");
String text = Files.readString(p);

Path is an immutable object representing a path, and Files is a collection of static utilities.

2) Line-by-line input/output

List<String> lines = Files.readAllLines(Path.of("data.txt"));
Files.write(Path.of("out.txt"), lines);   //Write the lines as they are

3) try-with-resources

try (BufferedReader br = Files.newBufferedReader(p)) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}
//br.close() is called automatically

Any resource that implements AutoCloseable can be used.

4) checked exception IOException

File IO methods are mostly checked exceptions that throw IOException. A throws IOException declaration or try/catch is required.

See as example

Example 1 — WriteFile.java: Write file

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

public class WriteFile {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("greeting.txt");
        Files.writeString(p, "Hello\nHello\n");
        System.out.println(p.toAbsolutePath() + "Write complete");
    }
}

Execution result

Completed writing /.../greeting.txt

Memo: If the file does not exist, it will be automatically created, and if it exists, it will be overwritten.

Example 2 — ReadFile.java: Reading file

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

public class ReadFile {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("greeting.txt");
        Files.writeString(p, "Hello\nHello\n");

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

Execution result

1: Hello
2: Hello

Note: Reading line by line makes things like numbering easier.

Example 3 — BufferedReadDemo.java : try-with-resources

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

public class BufferedReadDemo {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("greeting.txt");
        Files.writeString(p, "Hello\nHello\n");

        try (BufferedReader br = Files.newBufferedReader(p)) {
            String line;
            int n = 0;
            while ((line = br.readLine()) != null) {
                n++;
                System.out.printf("L%d: %s%n", n, line);
            }
        }
    }
}

Execution result

L1: Hello
L2: Hello

Note: br.close() is automatically called at the end of the try block.

Example 4 — AppendAndDelete.java: Add + Delete

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

public class AppendAndDelete {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("notes.txt");
        Files.writeString(p, "first line\n");
        Files.writeString(p, "Second line\n", StandardOpenOption.APPEND);
        System.out.println(Files.readString(p));
        Files.deleteIfExists(p);
        System.out.println("Deletion complete");
    }
}

Execution result

first line
second line

Deletion complete

Memo: StandardOpenOption.APPEND can be added after existing content.

Common Mistakes

  1. OS handle leak due to not closing file resources → Use try-with-resources
  2. Hard-code the path separator for each OS → Use Path.of / Path.resolve
  3. Korean text is broken because encoding is not specified → Files.readString(path, StandardCharsets.UTF_8) is recommended
  4. Propagate without having to use IOException every time → In the introductory stage, throws IOException in main is sufficient.
  5. Does not consider situations where multiple threads are writing the same file at the same time (outside the scope of this tutorial)

Cleanup

  • Path + Files is the center of modern Java IO
  • try-with-resources is the standard pattern for resource release
  • Large files are processed line by line + buffering is safe
  • UTF-8 encoding is recommended.

Try it yourself

cd 04_Exception_Input/Output/16_File_IO/src
javac WriteFile.java
java WriteFile

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/AppendAndDelete.javaJava
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class AppendAndDelete {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("notes.txt");
        Files.writeString(p, "first line\n");
        Files.writeString(p, "Second line\n", StandardOpenOption.APPEND);
        System.out.println(Files.readString(p));
        Files.deleteIfExists(p);
        System.out.println("Deletion complete");
    }
}
src/BufferedReadDemo.javaJava
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class BufferedReadDemo {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("greeting.txt");
        Files.writeString(p, "Hello\nHello\n");

        try (BufferedReader br = Files.newBufferedReader(p)) {
            String line;
            int n = 0;
            while ((line = br.readLine()) != null) {
                n++;
                System.out.printf("L%d: %s%n", n, line);
            }
        }
    }
}
src/ReadFile.javaJava
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class ReadFile {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("greeting.txt");
        Files.writeString(p, "Hello\nHello\n");

        List<String> lines = Files.readAllLines(p);
        for (int i = 0; i < lines.size(); i++) {
            System.out.println((i + 1) + ": " + lines.get(i));
        }
    }
}
src/WriteFile.javaJava
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class WriteFile {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("greeting.txt");
        Files.writeString(p, "Hello\nHello\n");
        System.out.println(p.toAbsolutePath() + "Write complete");
    }
}

Assignment

Problem 1 — Writing/reading TODO files

  • File name: Homework01.java
  • Core concepts: Files.write, Files.readAllLines

Requirements

  • Write the following 3 lines to file todo.txt: milk fraud, finish homework, 30 minutes of exercise
  • Read again and output in 1) ... format.
  • Delete the file when finished.

Expected output

1) Buying milk
2) Finish your homework
3) 30 minutes of exercise
Deletion complete

Problem 2 — Counting Words

  • File name: Homework02.java
  • Core concepts: Files.readString, split

Requirements

  • Write Java is fun. Java is powerful. to essay.txt.
  • Separates words based on Space/Punctuation and outputs the total number of words.
  • Delete the file when finished.

Expected output

number of words=6

Hint

  • text.split("[\\s.]+")

Check the correct answer

After solving it yourself, compare it with the reference solution below.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

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

/** Create/read/delete TODO files.*/
public class Homework01 {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("todo.txt");
        Files.write(p, List.of("milk fraud", "finish homework", "30 minutes of exercise"));
        List<String> lines = Files.readAllLines(p);
        for (int i = 0; i < lines.size(); i++) {
            System.out.println((i + 1) + ") " + lines.get(i));
        }
        Files.deleteIfExists(p);
        System.out.println("Deletion complete");
    }
}
Homework02.javaJava
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/** Read a file and count words.*/
public class Homework02 {
    public static void main(String[] args) throws IOException {
        Path p = Path.of("essay.txt");
        Files.writeString(p, "Java is fun. Java is powerful.");
        String text = Files.readString(p).trim();
        String[] words = text.split("[\\s.]+");
        int count = 0;
        for (String w : words) if (!w.isEmpty()) count++;
        System.out.println("number of words=" + count);
        Files.deleteIfExists(p);
    }
}

Learn this lesson with a mentor

Work through the Java + Spring Boot track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now