Get the number of lines and characters in a file using Java

This example demonstrates one of the ways to find the number of lines and characters in a file using Java Programming Language

Here is the block of code that will make the task easy for you

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

/**
 * Website: www.codedbug.com
 * @author Sudhanshu
 */
public class ReadWriteLineNumber {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
           LineNumberReader lnr;
           File f=new File("E://codedbug//file.txt");
            /*
           FileReader fr=new FileReader(f);
           lnr=new LineNumberReader(fr);
           */
            lnr = new LineNumberReader(new FileReader(new File("E://codedbug//file.txt")));
            int ln = 0;
            while (lnr.readLine() != null){
                ln++;
            }
            System.out.println("Total number of lines : " + ln+" Length of file: "+f.length());
            lnr.close();
    }
}

 

The file named “file.txt” here in this example is located inside the folder named codedbug on drive E. Change the address in the above program to point the file you want to find the number of lines and characters of.

Here is the visual view of the file “file.txt” and sample contents.
Input File

When we will run this program for the above file and with sample contents in the image. It will produce an output as:
Output
Total number of lines : 3 Length of file: 94