In this tutorial, you will learn how to Count the Number of Lines in a File in java. To understand it better, you may want to check the following first:
Java Program to Count the Number of Lines in a File
First, save the content in a text file with the same name that you enter in a program.
For this example, a text file saved with the name javaCode.txt
javaCode.txt
Welcome to Simple2Code.
Let Start
first tutorial
second Program
Source Code:
//count number of lines in a file
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class LineCount
{
public static void main(String[] args) throws IOException
{
File f = new File("javaCode.txt");
int count=0;
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s;
while((s=br.readLine())!=null) //Reading Content
{
count++; //increases for each line
}
fr.close();
//Display number of line
System.out.println("Total number of line:"+count);
}
}
Output:
Total number of line: 4