Java Read File with Files.readAllLines() API

In this example, I show you how to read all the lines from a file in Java using Files.readAllLines() API.

java.nio.file.Files.readAllLines() API

This method read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.

Java Files.readAllLines() API Example

In this example, we are reading all the lines of below JavaReadFile.java program itself.
package net.javaguides.corejava.io;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class JavaReadFile {

    public static void main(String[] args) throws IOException {

        Path myPath = Paths.get("src/net/javaguides/corejava/io/JavaReadFile.java");

        List < String > lines = Files.readAllLines(myPath, StandardCharsets.UTF_8);

        lines.forEach(line - > System.out.println(line));
    }
}
Output:
package net.javaguides.corejava.io;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class JavaReadFile {

    public static void main(String[] args) throws IOException {
        
        Path myPath = Paths.get("src/net/javaguides/corejava/io/JavaReadFile.java");
        
        List<String> lines = Files.readAllLines(myPath, StandardCharsets.UTF_8);
        
        lines.forEach(line -> System.out.println(line));
    }
}


Note: Files.readAllLines() is not intended for reading large files.
From the above program, Files.readAllLines() takes a file path and the charset as parameters:
List<String> lines = Files.readAllLines(myPath, StandardCharsets.UTF_8);
With forEach(), we go through the list and print all lines.
lines.forEach(line -> System.out.println(line));

Reference


Comments