Files.readString() / Files.readAllLines()
| Since: | Java 11(2018) |
|---|
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
FilesReadstring.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
class FilesReadstring {
public static void main(String[] args) throws IOException {
Path path = Path.of("sample.txt");
Files.writeString(path, "// first line\nHello, World!\n// last line");
String content = Files.readString(path);
System.out.println(content);
List<String> lines = Files.readAllLines(path);
System.out.println("Line count: " + lines.size());
for (String line : lines) {
System.out.println(line);
}
try (var stream = Files.lines(path)) {
stream
.filter(line -> line.startsWith("//"))
.forEach(System.out::println);
}
}
}
The command looks like this:
javac FilesReadstring.java java FilesReadstring // first line Hello, World! // last line Line count: 3 // first line Hello, World! // last line // first line // last line
Common Mistakes
Common Mistake 1: Specifying a non-existent file path causes NoSuchFileException
Okabe Rintaro tried to read a non-existent file with readString(), resulting in a NoSuchFileException.
ReadStringNg.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
class ReadStringNg {
public static void main(String[] args) throws IOException {
String content = Files.readString(Path.of("missing.txt"));
System.out.println(content);
}
}
The command looks like this:
javac ReadStringNg.java java ReadStringNg Exception in thread "main" java.nio.file.NoSuchFileException: missing.txt at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92) at ReadStringNg.main(ReadStringNg.java:7)
As Makise Kurisu fixed it, check with Files.exists() first, or wrap the call in a try-catch block to handle the exception gracefully.
ReadStringOk.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
class ReadStringOk {
public static void main(String[] args) {
Path path = Path.of("missing.txt");
try {
String content = Files.readString(path);
System.out.println(content);
} catch (IOException e) {
System.out.println("File not found: " + path);
}
}
}
The command looks like this:
javac ReadStringOk.java java ReadStringOk File not found: missing.txt
Common Mistake 2: Loading a large file with readString() all at once causes OutOfMemoryError
Shiina Mayuri tried to load a multi-gigabyte log file all at once with readString(), causing an OutOfMemoryError.
ReadStringOomNg.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
class ReadStringOomNg {
public static void main(String[] args) throws IOException {
String content = Files.readString(Path.of("huge_log.txt"));
System.out.println(content.length());
}
}
The command looks like this:
javac ReadStringOomNg.java java ReadStringOomNg Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
As Hashida Itaru fixed it, processing a large file line by line with BufferedReader keeps memory usage low.
ReadStringOomOk.java
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
class ReadStringOomOk {
public static void main(String[] args) throws IOException {
int count = 0;
try (BufferedReader reader = Files.newBufferedReader(Path.of("huge_log.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
count++;
}
}
System.out.println("Line count: " + count);
}
}
The command looks like this:
javac ReadStringOomOk.java java ReadStringOomOk Line count: 1000000
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.