- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to count the number of lines in a text file using Java?
To count the number of lines in a file
- Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor.
- Read the contents of the file to a bytearray using the read() method of FileInputStream class.
- Instantiate a String class by passing the byte array obtained, as a parameter its constructor.
- Now, split the above string into an array of strings using the split() method by passing the regular expression of the new line as a parameter to this method.
- Now, find the length of the obtained array.
Example
import java.io.File; import java.io.FileInputStream; public class NumberOfCharacters { public static void main(String args[]) throws Exception{ File file = new File("data"); FileInputStream fis = new FileInputStream(file); byte[] byteArray = new byte[(int)file.length()]; fis.read(byteArray); String data = new String(byteArray); String[] stringArray = data.split("\r
"); System.out.println("Number of lines in the file are ::"+stringArray.length); } }
data

Output
Number of lines in the file are ::3
- Related Articles
- How to count the number of words in a text file using Java?
- Counting number of lines in text file using java\n
- How to count the number of characters (including spaces) in a text file using Java?
- C# Program to count the number of lines in a file
- C Program to count the number of lines in a file?
- Count Duplicate Lines in a Text File on Linux
- How to count the total number of lines in the file in PowerShell?
- How to Copy Odd Lines of Text File to Another File using Python
- How to write multiple lines in text file using Python?
- Count lines in a file using Linux bash
- Counting number of characters in text file using java
- Java program to delete duplicate lines in text file
- C program to count characters, lines and number of words in a file
- How to Count Word Occurrences in a Text File using Shell Script?
- Counting number of paragraphs in text file using java\n

Advertisements