In this tutorial, I will show you How to get the Line Number of File using Java. The example code were tested and attached in the same post.

In a text file number of lines can be calculated by using the java.io.LineNumberReader class. we can use readLine() method to count the line from the file. The following program will give you idea about usage of LineNumberReader class.

CountLineNumber.java

package com.dineshkrish.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
/**
* 
* @author Dinesh Krishnan
*
*/
public class CountLineNumber {
public static void main(String[] args) {
// Defining File Object
File file = new File("c://Users//dineshk//Desktop//line_number.txt");
FileReader fileReader = null;
try {
fileReader = new FileReader(file);
// Defining LineNumberReader Object
LineNumberReader lineReader = new LineNumberReader(fileReader);
int lineCount = 0;
while(lineReader.readLine() != null) {
++lineCount;
}
System.out.println("The Total Number of Lines is : "+lineCount);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

Sample File Content

This is Line Number 1
This is Line Number 2
This is Line Number 3
This is Line Number 4
This is Line Number 5
This is Line Number 6
This is Line Number 7
This is Line Number 8
This is Line Number 9
This is Line Number 10

Output

——————

The Total Number of Lines is : 10

References

1. Stack Overflow

2. Java API Documentation

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *