Skip to content

Instantly share code, notes, and snippets.

@SriramKeerthi
Created January 2, 2016 15:37
Show Gist options
  • Save SriramKeerthi/c44b1019d85791ac01c3 to your computer and use it in GitHub Desktop.
Save SriramKeerthi/c44b1019d85791ac01c3 to your computer and use it in GitHub Desktop.
Counts the number of lines in a text file in Java
import java.io.BufferedReader;
import java.io.FileReader;
/**
* Reads a file from the command line parameter and counts the number of lines in it
* @author Sriram
*/
public class FileLineCount
{
public static void main( String[] args ) throws Exception
{
int lineCount = 0;
// Open a reader to read the file
try ( BufferedReader br = new BufferedReader( new FileReader( args[0] ) ) ) {
// Read the file line by line until there are no more lines
while ( br.readLine() != null ) {
// Increase the line count if line isn't null
lineCount++;
}
}
System.out.println( "Lines found: " + lineCount );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment