×

java · level 2 · unit 7 · lesson 2

  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

A keeps your text after the program ends.

Everything in your boxes vanishes when a program ends. A file keeps it. names the path to a file in the current folder, and Files.writeString(path, text) saves text there, making the file or replacing what it held.

Files.readString(path) reads it all back as one string, and Files.exists(path) checks whether the file is there. All three live in java.nio.file, so import java.nio.file.*.

Files can fail in ways that are nobody's fault, so these methods throw , a checked exception. The simplest way to deal with it is to declare it: main(String[] args) throws IOException.

import java.io.IOException;
import java.nio.file.*;
public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("diary.txt");
        System.out.println("Exists before: " + Files.exists(path));
        Files.writeString(path, "Dear diary, I learned about files today.");
        System.out.println("Exists after: " + Files.exists(path));
        System.out.println(Files.readString(path));
    }
}

Write a file before you read it, or Java stops with a NoSuchFileException.