Skip to main content

How do I read first n lines from a File

In this Q&A, we'll go over a few options provided by Java IO APIs to read lines from a file

This can be achieved with or without Java 8 Stream APIs.  One non Stream option is to use BufferedReader.readLine  method.   See demo code below:
try(BufferedReader br = new BufferedReader(new FileReader("c://lines.txt"))) {
    int i = 1; String l;
    while (( l = br.readLine()) != null) {
        System.out.println(l);
        if (++i > 10) break;
    }
}

Files class provides a method to Stream lines of text.  With a Stream object we can skip or limit the  lines that we read.  Note that the Stream is an autocloseable object.  So it can be used in a try-with-resources block

See demo code below:
String fileName = "c://lines.txt";
//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    stream.limit(10).forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

Comments