TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java Line Count for File

Use the BufferedReader class and readLine to count lines in a text file.
Line count. A text file has line separators in it. With a method like readLine on BufferedReader, we can count these lines in a file.
With readLine, we can handle all kinds of newline sequences (UNIX and Windows) with no effort on our part. A BufferedReader can be made from a Reader instance (like FileReader).
Our example. This program might throw an IOException, so it has the "throws IOException" notation at its top. It includes classes from the java.io namespace.

ReadLine: This method returns null when no more lines exist in the file (at end-of-file). We call it repeatedly.

LineCount: This int is incremented on each valid line read—when readLine does not return null.

Important: Make sure to change the file name passed to FileReader to one that exists on your system.

Java program that counts lines in file import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Program { public static void main(String[] args) throws IOException { int lineCount = 0; // Get BufferedReader. BufferedReader reader = new BufferedReader(new FileReader("C:\\programs\\example.txt")); // Call readLine to count lines. while (true) { String line = reader.readLine(); if (line == null) { break; } lineCount++; } reader.close(); // Display the line count. System.out.println("Line count: " + lineCount); } } Contents of example.txt: HELLO FROM DOT NET PERLS Output Line count: 3
Notes, in-memory files. For a file that is resident in memory, we can use a for-loop and scan for a known newline character. This would be faster than loading it from disk.For
A summary. Sometime simple is best. Many line-counting methods can be used. We could even cache a file's line count as it is read in, and then retrieve that value when needed.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf