- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting number of lines in text file using javan
We can read lines in a file using BufferedReader class of Java. See the example below −
Example
Consider the following text file in the classpath.
test.txt
This is Line 1 This is Line 2 This is Line 3 This is Line 4 This is Line 5 This is Line 6 This is Line 7 This is Line 8 This is Line 9 This is Line 10
Tester.java
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; public class Tester { private static final String FILE_PATH = "data.txt"; public static void main(String args[]) throws IOException { FileUtil fileUtil = new FileUtil(FILE_PATH); System.out.println("No. of lines in file: " + fileUtil.getLineCount()); } } class FileUtil { static BufferedReader reader = null; public FileUtil(String filePath) throws FileNotFoundException { File file = new File(filePath); FileInputStream fileStream = new FileInputStream(file); InputStreamReader input = new InputStreamReader(fileStream); reader = new BufferedReader(input); } public static int getLineCount() throws IOException { int lineCount = 0; String data; while((data = reader.readLine()) != null) { lineCount++; } return lineCount; } }
This will produce the following result −
Output
No. of lines in file: 10
- Related Articles
- Counting number of characters in text file using java
- Counting number of paragraphs in text file using java\n
- How to count the number of lines in a text file using Java?
- Java program to delete duplicate lines in text file
- How to Copy Odd Lines of Text File to Another File using Python
- How to write multiple lines in text file using Python?
- How to count the number of words in a text file using Java?
- How to count the number of characters (including spaces) in a text file using Java?
- Count Duplicate Lines in a Text File on Linux
- Counting divisors of a number using JavaScript
- Delete Lines in a Text File That Contain a Specific String
- Counting the number of groups Java regular expression
- Reading a Text file in java
- How to Find Line Number of a Given Word in text file using Python?
- C# Program to count the number of lines in a file

Advertisements