Sometimes you just want to count the number of lines in the file, rather than reading the file and performing some logic. The easiest way, I feel, is to use LineNumberReader for counting the lines. LineNumberReader class has a method getLineNumber() that gives the current line number of the file. So the logic is; to read all the lines of the files using the LineNumberReader until you reach the end and then use getLineNumber() method to get the current line number.
Example code
If you have a file with lines as follows -
This is a test file.
Line number reader is used to read this file.
This program will read all the lines.
It will give the count.
Then you can get the count of lines using the following code -
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class LineNumberDemo {
public static void main(String[] args) {
LineNumberReader reader = null;
try {
reader = new LineNumberReader(new FileReader(new File("F:\\abc.txt")));
// Read file till the end
while ((reader.readLine()) != null);
System.out.println("Count of lines - " + reader.getLineNumber());
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Output
Count of lines – 4
Printing lines of the file with line number
If you want to print lines of the file along with the line number you just need to tweak the above code a little.
Java code
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class LineNumberDemo {
public static void main(String[] args) {
LineNumberReader reader = null;
try {
reader = new LineNumberReader(new FileReader(new File("F:\\abc.txt")));
String str;
// Read file till the end
while ((str = reader.readLine()) != null){
System.out.println(reader.getLineNumber() + "- " + str);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Output
1- This is a test file.
2- Line number reader is used to read this file.
3- This program will read all the lines.
4- It will give the count.
That's all for this topic How to count lines in a File - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -