In this example we will show how to get the total number of lines of a file in Java.
Source Code
package com.beginner.examples;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileOperator17Example {
public static void main(String[] args) {
try
{
File path = new File("example.txt");
if (!path.exists())
{
path.createNewFile();
}
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
int lines = 0;
while (br.readLine() != null)
{
lines++;
}
System.out.println("Lines : " + lines);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Output:
Lines : 3
References
Imported packages in Java documentation: