×

java · level 2 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

closes your files for you, even after an error.

For bigger files, write bit by bit with a . It collects text and writes it in batches, so you must it at the end, or the last batch may never reach the file. People forget, and an exception can skip the line that closes it.

Try-with-resources solves both. Open the writer inside the try brackets: try (BufferedWriter out = Files.newBufferedWriter(path)) { }. When the block ends, Java closes it for you, even after an exception.

.write adds text and .newLine() ends the line. To read back, open new Scanner(path) the same way, and loop while is true.

import java.io.*;
import java.nio.file.*;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("todo.txt");
        String[] jobs = {"Feed the cat", "Water the plants", "Do homework"};
        try (BufferedWriter out = Files.newBufferedWriter(path)) {
            for (String job : jobs) {
                out.write(job);
                out.newLine();
            }
        }
        try (Scanner in = new Scanner(path)) {
            while (in.hasNextLine()) {
                System.out.println("To do: " + in.nextLine());
            }
        }
    }
}

A try with brackets needs no catch, but you can add one.