2 ways to Count number of lines in file in java



We will read c:/myFile.txt


c:/myFile.txt looks like this >
line 1
line 2
line 3
line 4


In this post we’ll write >
  • Program 1 to Count number of lines in file using BufferedReader in java file IO
  • Program 2 to Count number of lines in file using LineNumberReader in java file IO




Program 1 to Count number of lines in file using BufferedReader in java file IO

BufferedReader's readLine() method reads whole line and return it in  String form, we will keep variable which will be incremented every time a line is read. We will read till end of file.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class CountLinesInFileUsingBufferedReader {
   public static void main(String... args) throws IOException {
          FileReader fr = null;
          BufferedReader br = null;
          fr = new FileReader("c:/myFile.txt");
          br = new BufferedReader(fr);
          int noOfLinesInFile = 0;
          while ((br.readLine()) != null) { // read till end of file
                 noOfLinesInFile++;
          }
          System.out.println("No of lines in file = " + noOfLinesInFile);
          br.close(); // close BufferedReader
                              // will close FileReader
   }
}
/* OUTPUT
No of lines in file = 4
*/


Program 2 to Count number of lines in file using LineNumberReader in java file IO

import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
/** JavaMadeSoEasy.com */
public class CountLinesInFileUsingLineNumberReader {
   public static void main(String... args) throws IOException {
          FileReader fr = null;
          LineNumberReader lnr = null;
          fr = new FileReader("c:/myFile.txt");
          lnr = new LineNumberReader(fr);
          int noOfLinesInFile = 0;
          while ((lnr.readLine()) != null) { // read till end of file
                 noOfLinesInFile++;
          }
          System.out.println("No of lines in file = " + noOfLinesInFile);
          lnr.close(); // close LineNumberReader
                              // will close FileReader
   }
}
/* OUTPUT
No of lines in file = 4
*/





RELATED LINKS>

Program to How to use Mark and Reset methods with BufferedReader

Difference between FileInputStream and BufferedInputStream in java file IO


Copy a file in java 2 in ways - use org.apache.commons.io.FileUtils's copyDirectory(sourceDirectory, destDirectory)


Program to Move a file - in java file IO


No comments:

Post a Comment