How to find total number of lines in a file in Java?

How to find total number of lines in a file in Java?


Posted in : Core Java Posted on : July 30, 2014 at 2:31 PM Comments : [ 0 ]

This tutorial teaches you the code for finding the total number of lines in a file in Java Program. You get the code for finding the total number of lines in a given text file.

Easiest code for finding total number of line in text file from Java program

In this tutorial I will explain you the Java code which can be used to find the total number of line in a given text file. Our program defines a variable call String fileName="datafile.txt" and then uses this variable to find the no of number of lines in the given file.

The easiest way to find the total no of lines in a files is to use the class BufferedReader class and then iterate through all the lines and then count the no of lines in the file.

A new line in the file starts when it there is "\n" or "\r" in the file data stream. The readLine() method of the BufferedReader class knows all these things and returns one line at a time.

So, we will use the following loop for counting the no of lines:

while( (str = bufferedReader.readLine()) != null) { 
 lines++; 
} 

Here is the lines in our "data.txt" file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Complete program to find the no of lines in a text file:

import java.io.*;
/*
* Java class for finding the no of lines in a text file
* using the BufferedReader class and readLine() method
*/
public class  NoOfLines
{
	public static void main(String[] args) 
	{
		System.out.println("Finding No of Lines in a file!!!");
		String fileName="datafile.txt";//Input file
		try{

		//BufferedReader object
		BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName)); 
		int lines = 0; 
		String str; 
		//Iterate through lines in the file
		while( (str = bufferedReader.readLine()) != null) { 
			lines++; 
		} 
		bufferedReader.close();
		//Pring no of lines in the file
		System.out.println("Line count: " + lines);
		}catch(Exception e){
			System.out.println("Error while counting no of lines in a file:" 
                 + e.getMessage());
		}
	}
}

If you run the the program it will display you the no of lines a the input file.

Read more Tutorials at File Handling in Java Tutorial Section.

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics