Sub topic 5
Reading a Whole File into Memory
This chapter assumes you know basic Java classes, String, List, Stream, and checked exceptions. The examples use Java 11 or later.
Choosing a whole-file method
The Files class provides convenient methods for small and moderate-sized files. These methods read all content before returning, so the complete file must fit comfortably in memory.
| Method | Result | Best for |
|---|---|---|
| `Files.readString` | One `String` | Text where you need the complete content |
| `Files.readAllLines` | `List<String>` | Text where each line should be processed separately |
Both methods remove line-ending characters from the strings they return in different ways. readString preserves the file's line-ending characters inside one string. readAllLines returns one string per line without the line-ending characters.
Reading text as a string
Files.readString accepts a Path and returns the complete text. The overload that accepts a Charset makes the encoding choice visible.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class ReadText {
public static void main(String[] args) {
Path file = Path.of("notes.txt");
try {
String text = Files.readString(file, StandardCharsets.UTF_8);
System.out.println(text);
} catch (IOException e) {
System.out.println("Could not read " + file + ": " + e.getMessage());
}
}
}Path.of creates the location object. It does not open the file. Files.readString performs the actual file-system operation. If the file does not exist, or the program lacks permission, the method throws an IOException subclass.
The no-charset overload uses UTF-8. Using StandardCharsets.UTF_8 documents the format and prevents the encoding choice from being hidden in the method call.
Reading lines into a list
Use Files.readAllLines when line boundaries matter. The returned list contains the file's lines in order.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class ReadLines {
public static void main(String[] args) throws IOException {
Path file = Path.of("notes.txt");
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
for (int i = 0; i < lines.size(); i++) {
System.out.println((i + 1) + ": " + lines.get(i));
}
}
}This example declares throws IOException, allowing the exception to reach the caller. A command-line program may instead catch it and print a useful message. Choose one approach consistently at the application boundary.
Common errors
- Passing a directory instead of a regular file can cause an I/O failure.
- Assuming every file is UTF-8 can corrupt non-UTF-8 text.
- Calling
readAllLinesfor a huge log file can exhaust memory. - Forgetting that
readAllLinesdoes not include newline characters in each list element. - Catching only
Exceptionhides useful distinctions. CatchNoSuchFileExceptionfirst when a missing file needs a special message.
Exercise
Which method should you choose when you need to print every line with its number, and why?
Show answer
Choose Files.readAllLines because it returns the content as an ordered List<String>, allowing each line to be accessed by index.