Reading and Writing Files

Files on your computer

Real programs save data to files so it's still there tomorrow. Java's java.nio.file.Files class makes simple file work a one-liner. Run these on your own computer (the browser editor in this course has no files to read):

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Paths.get("notes.txt");

        // Write: creates the file, or replaces what was in it
        Files.write(file, Arrays.asList("Buy milk", "Call Asha"));

        // Read every line back
        List<String> lines = Files.readAllLines(file);
        for (String line : lines) {
            System.out.println("- " + line);
        }
    }
}

Running it creates notes.txt and prints:

- Buy milk
- Call Asha

File methods throw IOException (a checked exception – the file might be missing), so the method must handle it or say throws IOException.

try-with-resources: closing things automatically

Things like open files must be closed when you're done. If you put them in the brackets of try ( ... ), Java closes them for you, even if an error happens. Here we read text line by line – from a String, so you can run it anywhere:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class Main {
    public static void main(String[] args) {
        String text = "apple\nbanana\ncherry";
        try (BufferedReader reader = new BufferedReader(new StringReader(text))) {
            String line;
            int number = 1;
            while ((line = reader.readLine()) != null) {
                System.out.println(number + ": " + line);
                number++;
            }
        } catch (IOException e) {
            System.out.println("Could not read: " + e.getMessage());
        }
    }
}

Output

1: apple
2: banana
3: cherry

To read a real file, swap new StringReader(text) for new FileReader("notes.txt"). readLine() returns null when there are no more lines.

Think of it like this: try-with-resources is like a library that takes the book back from you automatically when you leave, so you can never forget to return it.

HOME LABS COMMUNITY DASHBOARD