Thursday, 30 October 2014

How to get The total number of lines in a file by using JAVA

Standard


In this Post we will see how to Read Total Number of Lines in File Using JAVA Application

In java by using LineNumberReader class we can get  the total number of lines in a file by looping theLineNumberReader.readLine() method.Let's go for code.



----------------------------------------------------------------------------------------------------------------------------------








----------------------------------------------------------------------------------------------------------------------------------
JAVA CODE :

  1. package com.system;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileReader;  
  5. import java.io.IOException;  
  6. import java.io.LineNumberReader;  
  7.   
  8. public class Test   
  9. {  
  10.     public static void main(String[] args)  
  11.     {     
  12.    
  13.         try{  
  14.    
  15.             File file =new File("D:\\file1234.txt");  
  16.    
  17.             if(file.exists()){  
  18.    
  19.                 FileReader fr = new FileReader(file);  
  20.                 LineNumberReader lnr = new LineNumberReader(fr);  
  21.                 
  22.                   
  23.                 int lineNum = 0;  
  24.    
  25.                     while (lnr.readLine() != null){  
  26.                           
  27.                         lineNum++;  
  28.                       
  29.                     }  
  30.    
  31.                     System.out.println("Total number of lines in the file : " + lineNum);  
  32.    
  33.                     lnr.close();  
  34.    
  35.    
  36.             }else{  
  37.                  System.out.println("File does not exists!");  
  38.             }  
  39.    
  40.         }catch(IOException e){  
  41.             e.printStackTrace();  
  42.         }  
  43.    
  44.     }  
  45. }  

0 comments:

Post a Comment