Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Files.readAllLines()

Reads a text file into a list of lines.

Available since: Java 8

Syntax

static List<String> readAllLines(Path path) throws IOException

Parameters

ParameterTypeDescription
pathPathThe 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 42

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.