Count total number of lines in text file

This example will count the number of lines in a text file using java, java 8, guava and apache commons. Each example should take into consideration reading a large file and memory management although I didn't run performance benchmarks. The text was generated using Samuel L. Ipsum.


URI fileLocation;

public void setUp() throws URISyntaxException {
    fileLocation = this.getClass()


File contents

Your bones don't break, mine do. 
That's clear. 
Your cells react to bacteria and viruses differently than mine. 
You don't get sick, I do. 
That's also clear. 
But for some reason, you and I react the exact same way to water. 
We swallow it too fast, we choke. 
We get some in our lungs, we drown. 
However unreal it may seem, we are connected, you and I. 
We're on the same curve, just on opposite ends.

Straight up Java

public void count_lines_text_java() throws IOException {

    LineNumberReader lineReader = new LineNumberReader(new FileReader(Paths

    long totalNumberOfLines = lineReader.getLineNumber() + 1;


    assertEquals(10, totalNumberOfLines);

Java 8

public void count_lines_text_java8() throws IOException, URISyntaxException {

    long numberOfLines;
    try (Stream<String> s = Files.lines(Paths.get(fileLocation),
            Charset.defaultCharset())) {

        numberOfLines = s.count();

    } catch (IOException e) {
        throw e;

    assertEquals(10, numberOfLines);

Google Guava

public void count_lines_text_file_guava() throws IOException {

    long linesCounted =
            Paths.get(fileLocation).toFile(), Charsets.UTF_8,
            new LineProcessor<Long>() {

                long numberOfLinesInTextFile = 0;

                public boolean processLine(String line) throws IOException {

                    return true;

                public Long getResult() {
                    return numberOfLinesInTextFile;

    assertEquals(10, linesCounted);

Apache Commons

public void count_lines_text_apache() throws IOException {

    LineIterator lineIterator = FileUtils.lineIterator(
            Paths.get(fileLocation).toFile(), Charset.defaultCharset()

    long linesInTextFile = 0;
    try {
        while (lineIterator.hasNext()) {
    } finally {

    assertEquals(10, linesInTextFile);