Sub topic 5
Reading a Whole File into Memory
This chapter assumes you can create a Path with Path.of, that you know what a checked exception is, and that you have used String, List and Stream. It also assumes Java 11 or later, because Files.readString arrived in Java 11.
Reading a whole file means loading all of its contents into memory with one method call. There is no loop, no reader and no cleanup. It is the right tool for small and medium text files such as configuration, templates, test fixtures and short logs. It is the wrong tool for files that might be larger than the memory you are willing to spend.
The three methods
The Files class has three methods for reading a complete file.
| Method | Returns | Decodes text? | Since |
|---|---|---|---|
| `Files.readString(Path)` | `String` | Yes, UTF-8 | Java 11 |
| `Files.readString(Path, Charset)` | `String` | Yes, your charset | Java 11 |
| `Files.readAllLines(Path)` | `List<String>` | Yes, UTF-8 | Java 7 (no-charset overload since Java 8) |
| `Files.readAllLines(Path, Charset)` | `List<String>` | Yes, your charset | Java 7 |
| `Files.readAllBytes(Path)` | `byte[]` | No | Java 7 |
Each method opens the file, reads it to the end, closes it, and returns the result. You never hold a resource, so no try-with-resources block is needed.
A first example
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class SmallFiles {
public static void main(String[] args) throws IOException {
Path file = Path.of("notes.txt");
Files.writeString(file, "first\nsecond\n");
String text = Files.readString(file);
List<String> lines = Files.readAllLines(file);
System.out.println(text.length());
System.out.println(lines.size());
}
}The program prints 13 and then 2. The string first\nsecond\n has 5 + 1 + 6 + 1 = 13 characters. The \n characters count, because readString returns the text exactly as stored. readAllLines splits the text into two elements, first and second.
Two details are worth remembering:
length()counts UTF-16charvalues, not bytes on disk. A file containingéin UTF-8 occupies two bytes but gives one character.readAllLinesremoves the line terminators. It accepts\n,\r\nand\r. A final terminator does not produce an extra empty element, so"a\nb\n"and"a\nb"both give two lines.
Choosing between String, lines and bytes
Pick the return type that matches what you do next.
- Use
readStringwhen you need the text as one unit. Examples are parsing JSON, applying a regular expression across line breaks, or comparing the whole content in a test. - Use
readAllLineswhen each line is a record, such as a list of names or a CSV without quoted newlines. You get random access withget(i)and can stream the list. - Use
readAllBytesfor binary data (images, archives, serialized objects) or when you want to decode the text yourself.
Working with the lines
Because readAllLines returns an ordinary List<String>, everything you know about collections applies. This example loads a file of key=value pairs into a map.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class LoadSettings {
public static void main(String[] args) throws IOException {
Path file = Path.of("settings.txt");
Files.writeString(file, "# comment\nhost=localhost\nport=8080\n\n");
Map<String, String> settings = new HashMap<>();
for (String line : Files.readAllLines(file)) {
String trimmed = line.strip();
if (trimmed.isEmpty() || trimmed.startsWith("#")) {
continue;
}
int eq = trimmed.indexOf('=');
if (eq > 0) {
settings.put(trimmed.substring(0, eq), trimmed.substring(eq + 1));
}
}
System.out.println(settings.get("host") + ":" + settings.get("port"));
}
}The output is localhost:8080. The list is a plain mutable ArrayList in current JDKs, but do not rely on that. Copy it if you need to modify it.
Encodings: the default and the failure mode
readString and readAllLines decode with UTF-8 unless you pass a Charset. This is deliberate. The older FileReader used the platform default charset before Java 18, so the same program could read the same file differently on two machines. The Files methods avoid that problem.
The decoder is strict. If the bytes are not valid in the chosen charset, the call throws MalformedInputException (a subclass of CharacterCodingException, which is an IOException). It does not silently insert replacement characters. The next example writes a Latin-1 file and shows both outcomes.
import java.io.IOException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class DecodeDemo {
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("latin1", ".txt");
// "caf" followed by the single byte 0xE9, which is "é" in ISO-8859-1
Files.write(file, new byte[] {'c', 'a', 'f', (byte) 0xE9});
try {
Files.readString(file);
} catch (CharacterCodingException e) {
System.out.println("Not valid UTF-8");
}
System.out.println(Files.readString(file, StandardCharsets.ISO_8859_1));
Files.delete(file);
}
}The program prints Not valid UTF-8 and then café. A lone 0xE9 byte is not a complete UTF-8 sequence, so the first call fails. ISO-8859-1 maps every byte to a character, so it never fails, but it can give wrong text if the file was really in another encoding.
A byte order mark (BOM) is another common surprise. Some Windows tools write a UTF-8 BOM at the start of a file. Java's UTF-8 decoder keeps it as the character \uFEFF, so the first line or the first key in your map can look correct but fail an equals comparison. If you expect such files, remove the leading \uFEFF after reading.
Memory limits
All three methods read the entire file before returning, so memory use grows with file size. Remember these figures:
readAllBytesallocates onebyte[]of the file size. Arrays are limited to about 2 GB, so larger files fail withOutOfMemoryError.readStringneeds the bytes and then the decoded string. Peak usage can be a small multiple of the file size.readAllLinescreates oneStringobject per line, which adds overhead for files with many short lines.
If the file size is under your control (a config file you ship), whole-file reads are safe. If users supply the file, either check Files.size(path) first and reject large inputs, or stream the data as shown in a later chapter. An OutOfMemoryError is an Error, not an IOException, so a catch (IOException e) block does not handle it.
Handling failures
The most common failures are all IOException subclasses, and you can catch them separately.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class ErrorDemo {
public static void main(String[] args) {
Path file = Path.of("missing.txt");
try {
System.out.println(Files.readString(file));
} catch (NoSuchFileException e) {
System.out.println("File not found: " + e.getFile());
} catch (IOException e) {
System.out.println("Read failed: " + e.getMessage());
}
}
}Catch the more specific exception first. Other failures you may see are AccessDeniedException when permissions block the read, and a plain IOException when the path is a directory. Both are also caught by the general handler.
Common mistakes
- Assuming platform encoding. Do not expect the JVM's default charset to apply.
Filesalways uses UTF-8 unless told otherwise. - Forgetting the relative path base.
Path.of("notes.txt")resolves against the working directory, which depends on how the program is launched. Printfile.toAbsolutePath()when a file seems to be missing. - Reading a file you are still writing. A whole-file read returns whatever is on disk at that moment. A concurrent writer can leave a partial result.
- Splitting text by hand.
text.split("\n")leaves stray\rcharacters on Windows-style files. UsereadAllLinesortext.lines()instead. - Using whole-file reads on unbounded input. Log files grow without limit. Plan for them to be large.
Exercise
A file named data.txt contains the bytes for "a\r\nb\r\n\r\n" in UTF-8. What does Files.readAllLines(Path.of("data.txt")) return, and what does Files.readString(Path.of("data.txt")).length() return?
Show answer
readAllLines returns a list of three elements: "a", "b" and "" (an empty string for the blank third line). The trailing terminator after the blank line does not add a fourth element. readString returns the text unchanged, which contains 8 characters: a, \r, \n, b, \r, \n, \r, \n.
Exercise
Your program reads user-supplied text files with Files.readString and sometimes fails with MalformedInputException. Give two reasonable responses, and say which response you should avoid.
Show answer
First, ask the supplier for the file's real encoding and pass it as a Charset argument, for example Files.readString(path, Charset.forName("windows-1252")). Second, reject the file with a clear message that says it must be valid UTF-8. Avoid switching to ISO-8859-1 only to silence the exception, because that decodes every byte without error and can produce wrong characters without any warning.