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
- Start with A
- Do this Write, then read
- Result A
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);
}
}
}
A
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 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
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);
}
}
}
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.