Files.readAllLines()
Reads a text file into a list of lines.
Available since: Java 8
Syntax
static List<String> readAllLines(Path path) throws IOExceptionParameters
| Parameter | Type | Description |
|---|---|---|
| path | Path | The path to the file. |
Return value
List<String>A mutable list of lines without the line break characters.
Examples
Summing numbers from a file:
void main() throws IOException {
Path file = Path.of("scores.txt");
Files.writeString(file, "10\n25\n7\n");
List<String> lines = Files.readAllLines(file);
int sum = 0;
for (String line : lines) {
sum += Integer.parseInt(line);
}
IO.println(lines.size() + " lines, sum " + sum);
Files.delete(file);
}Output:
3 lines, sum 42Notes
The whole file is loaded into memory. For large files processed line by line, Files.lines() is better. The method appeared in Java 7 with a required charset, and in Java 8 in a version that defaults to UTF-8.
See also
- Files.lines() — Reads a file lazily as a stream of lines, without loading it into memory.
- Files.readString() — Reads a whole text file into one string.
- Files.writeString() — Writes a string to a file, creating or overwriting it.
Related recipes
In the tutorial
- Reading and writing files — Reading and writing text files in Java — Files.writeString, readString, readAllLines, write, appending to the end, Files.lines and buffered streams.