Files.readString() / Files.readAllLines()
Methods for reading a file's contents as a string or a list of lines in a single call (Java 11+). Using the utility methods of the Files class lets you read files with less code than traditional BufferedReader approaches.
Syntax
// Reads the entire file as a string (Java 11+).
String content = Files.readString(Path.of("file-path"));
// Reads all lines of the file as a list.
List<String> lines = Files.readAllLines(Path.of("file-path"));
// Reads all lines of the file as a stream (Java 8+).
Stream<String> lineStream = Files.lines(Path.of("file-path"));
// Creates a path object (Java 11+).
Path path = Path.of("file-path");
Method List
| Method | Description |
|---|---|
| Files.readString(Path) | Reads the entire file as a UTF-8 string (Java 11+). You can also specify a character encoding as the second argument. |
| Files.readAllLines(Path) | Reads all lines of the file as a List<String>. Line endings are not included. |
| Files.lines(Path) | Returns all lines of the file as a Stream<String> (Java 8+). Useful for lazily reading large files. |
| Path.of(String) | Creates a path object from a string (Java 11+). Equivalent to Paths.get(). |
Sample Code
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
// Reads the entire file as a string (Java 11+).
try {
String content = Files.readString(Path.of("sample.txt"));
System.out.println(content); // Prints the file contents.
} catch (IOException e) {
e.printStackTrace();
}
// Reads all lines of the file as a list.
try {
List<String> lines = Files.readAllLines(Path.of("sample.txt"));
System.out.println("Line count: " + lines.size());
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Processes lines using a stream (useful for large files).
try (var stream = Files.lines(Path.of("sample.txt"))) {
stream
.filter(line -> line.startsWith("//"))
.forEach(System.out::println); // Prints only comment lines.
} catch (IOException e) {
e.printStackTrace();
}
Notes
Both readString() and readAllLines() load the entire file into memory, so reading very large files (several hundred MB or more) may cause an out-of-memory error. For large files, use Files.lines() or BufferedReader to process the file one line at a time.
Because Files.lines() returns a Stream, use it inside a try-with-resources block. If you do not close the stream, the file handle will not be released. The default encoding is UTF-8; if your file uses a different encoding, pass a Charset as the second argument (e.g., Charset.forName("Shift_JIS")).
For writing to files, see Files.writeString() / Files.write().
If you find any errors or copyright issues, please contact us.