How to get Count of Lines in the file in java?

Here is a some example to explain how to get Count of Lines in the file.

File in D:/tmp/nourit.txt with the Content.

IT Training Center for Java and Web technology. 
If you enjoy and like our tutorials and believe in our mission, 
Please Subscribe us on Youtube and follow us on Twitter, 
or befriend us on Facebook or Google Plus.

Lets start:

  • First example for total number of lines in the File with Java 8
package com.nourit.javaIO;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author NOUR-IT.com
 *
 */
public class CountOfLines {

  public static void main(String[] args) {
    // for total number of lines in the File with Files.lines
    try {
      long countOfLines = Files.lines(Paths.get(new File("D:/tmp/nourit.txt").getPath())).count();
      System.out.println(String.format("There are %s lines in the document", countOfLines));
    } catch (IOException e) {
      System.out.println("No File Found");
    }

  }
}

Second example for total number of lines in the File with LineNumberReader

package com.nourit.javaIO;

import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
/**
 * @author NOUR-IT.com
 *
 */
public class CountOfLines1 {

  public static void main(String[] args) {
    try {
      FileReader fr = new FileReader("D:/tmp/nourit.txt");
      LineNumberReader lnr = new LineNumberReader(fr);

      int countOfLines = 0;

      while (lnr.readLine() != null) {
        countOfLines++;
      }

      lnr.close();
      System.out.println(String.format("There are %s lines in the document", countOfLines));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Output:

There are 4 lines in the document

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*