Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » Networking TechnologyRSS Feeds

Program that will count the number of lines in each file that is specified on the command line

Posted By: Ludwik Fischer     Category: Java     Views: 8868

Write a program that will count the number of lines in each file that is specified on the command line. Assume that the files are text files. Note that multiple files can be specified, as in "java LineCounts file1.txt file2.txt file3.txt". Write each file name, along with the number of lines in that file, to standard output. If an error occurs while trying to read from one of the files, you should print an error message for that file, but you should still process all the remaining files.

Code for Program that will count the number of lines in each file that is specified on the command line in Java

import java.io.*;

class cntlines
{
          
      publicstaticvoid main(String args[]) throws IOException
      {
    
    try
    {
      FileReader fr;
          BufferedReader br;
          File f;
          String str;
          int i=0,cnt=0;
          while(args[i] != null)
          {
            f = new File(args[i]);
            fr = new FileReader(f);
        br = new BufferedReader(fr);
           
        while((str = br.readLine()) != null)
            cnt++;
            System.out.println("File Name : " + f.getName() + " Total Lines : " + cnt);
            cnt = 0;  
            i++;   
            fr.close();
          }  
      
    }
    catch(FileNotFoundException e)
     {
      System.out.println("File Not Found");
    }
    catch(IOException e)
        {
      System.out.println("Exception : " + e);
    } 
      }
}
/*
Output

File Name : cntwords.java Total Lines : 168
File Name : data.txt Total Lines : 1
File Not Found

*/
  
Share: 



Ludwik Fischer
Ludwik Fischer author of Program that will count the number of lines in each file that is specified on the command line is from Frankfurt, Germany.
 
View All Articles

Related Articles and Code:


 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!