Lesson contents

Java — Reading files with try-with-resources

In Java, Files.lines opens a stream of text lines. Use try-with-resources so the stream and its file close when processing finishes, including after an exception.

A simple example

Read back one letter

  1. Start with A
  2. Do this Write, then read
  3. Result A
A file stores the letter between the write and the read.
Main.java
import java.nio.file.*;
class Main {
    public static void main(String[] args) throws Exception {
        Path file = Files.createTempFile("letter", ".txt");
        try {
            Files.writeString(file, "A");
            System.out.println(Files.readString(file));
        } finally {
            Files.delete(file);
        }
    }
}
Output
A
Advertisements

Sum two lines from a temporary report

Files.lines returns a lazy stream backed by an open file. Try-with-resources closes it before the outer finally deletes the temporary path. The terminal sum operation reads the stream.

Morning returns: 4. Afternoon returns: 7. End of day: 11.
Read a two-line count sheet

Morning staff record four returns in a file and afternoon staff record seven on the next line. Read each line as a number and add it to the running total. The day ends with eleven returns.

Run the example

Java 17 or later. Run these commands from the directory containing the example.

java Main.java
Main.java
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

class Main {
    public static void main(String[] args) throws java.io.IOException {
        Path path = Files.createTempFile("readings", ".txt");
        try {
            Files.writeString(path, "4\n7\n");
            try (Stream<String> lines = Files.lines(path)) {
                int total = lines.map(String::strip).filter(s -> !s.isEmpty())
                                 .mapToInt(Integer::parseInt).sum();
                System.out.println(total);
            }
        } finally {
            Files.deleteIfExists(path);
        }
    }
}
Output
11

The file contains two whole-number readings on separate lines. Reading from the beginning gives 4 and 7, for a total of 11. The example creates its own file, so it can run in a clean working directory.

Try it yourself

Add a third line containing 12.

Check your answer

The new total is 23. This report format assumes valid integer readings. When accepting external input, apply the validation techniques from the preceding lesson.

Java language tutorials

Related tags

  • Java
  • files
  • streams
  • resource management