Showing posts with label line count. Show all posts
Showing posts with label line count. Show all posts

File handling - Command Line Arguments - Line count

// File handling
// Command Line Arguments

/*
Write a Java program LineCounts.java that will count the number of lines in each files that is specified on the command line. Note that multiple files can be specified, as in               
    
     java LineCounts file1.txt file2.txt file3.txt
*/

import java.io.*;

class LineCounts
{
     public static void main(String as[]) throws IOException
     {
          for(int i=0;i<as.length;i++)
          {
              FileReader fr = new FileReader(as[i]);
              BufferedReader br = new BufferedReader(fr);
              int linecount=0;
              while(true)
              {
                   String str = br.readLine();
                   if(str==null)
                        break;
                  
                   linecount++;
              }
              fr.close();
              System.out.println(as[i]+" = "+linecount);
          }
     }
}

Java - File handling - line, word and character count


// File handling

/*
Write a Java program that displays the number of characters, lines and words in a text file.
*/

import java.io.*;

class FileLWC
{
     public static void main(String as[]) throws IOException
     {
         
          FileInputStream fin = new FileInputStream("ipt.txt");
          int lc = 0, wc = 0, cc = 0;
         
          while(true)
          {
              int i = fin.read();
              if(i==-1)
              {
                   lc++;
                   wc++;
                   break;
              }
              char c = (char)i;
             
              if(c=='\n' || c=='.')
              {
                   lc++;
                   wc++;
              }
              else if(c=='\t' || c==' ')
                   wc++;
              else if((c>='a' && c<='z')||(c>='A' && c<='Z'))
                   cc++;
                            
          }       
          System.out.println("Line count = "+lc);
          System.out.println("Word count = "+wc);
          System.out.println("Character count = "+cc);
          fin.close();
     }
}

File Handling 11: File line, word and character count

# Count number of characters, words and lines in a file
# File Count

fs = open("ipt.txt", "r")

charcount = 0
wordcount = 0
linecount = 0

all_lines = fs.readlines()
linecount = len(all_lines)

for Line in all_lines:
Line = Line.strip().lower()

tmp = Line.split(" ")
wordcount += len(tmp)

for ch in Line:
if(ch.isalpha()):
charcount += 1

print("Number of characters in file =", charcount)
print("Number of words in file =", wordcount)
print("Number of lines in file =", linecount)

fs.close()