Java Read File Example

In this source code example, we show you how to read all lines from a file in Java.

We use Files.readAllLines() method to read all lines from a given file.

Java Read File Example

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/resources/sample.txt");
        
        List<String> lines = Files.readAllLines(myPath, StandardCharsets.UTF_8);
        
        lines.forEach(line -> System.out.println(line));
    }
}

References


Comments