Count lines of a particular file

In this section, you will learn how to count the availability of text lines in the particular file. A file is read before counting lines of a particular file, . File is a collection of stored information that are arranged in string, rows, columns and li

Count lines of a particular file

In this section, you will learn how to count the availability of text lines in the particular file. A file is read before counting lines of a particular file, . File is a collection of stored information that are arranged in string, rows, columns and li

Count lines of a particular file

In this program you will learn how to read a file and count number of lines in it. This is the simple program that opens a file and read one line at a time and count no of lines in a file.

Program first asks the user to enter the extension of the file and then it reads all the files with the input extension. Its reads the file(s) and then prints the no of lines in each file.

Java provides many API's for reading, writing, updating and deleting the file. You can also update the file content using Java programs.

We have used the following class in the program:

  • BufferedReader
  • InputStreamReader
  • FileReader
  • LineNumberReader

Here is the code of the program:

 
import java.io.*;

public class NumberOfLine{
	public static void main(String[] args) {
		try{
			System.out.println("Getting line number of a paritcular file example!");
			BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("Please enter file name with extension:");
			String str = bf.readLine();
			File file = new File(str);
			if (file.exists()){
				FileReader fr = new FileReader(file);
				LineNumberReader ln = new LineNumberReader(fr);
				int count = 0;
				while (ln.readLine() != null){
					count++;
				}
				System.out.println("Total line no: " + count);
				ln.close();
			}
			else{
				System.out.println("File does not exists!");
			}
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}
}

Download this example.

Use javac compiler to compile the file and to run the program you have use the java command on command prompt. 

C:\myexamples\Math_package>javac NumberOfLine.java

C:\myexamples\Math_package>java NumberOfLine
Getting line number of a paritcular file example!
Please enter file name with extension:
AddTwoBigNumbers.shtml
Total line no: 58