View Single Post
Join Date: Jul 2008
Posts: 28
Reputation: newtechie is an unknown quantity at this point 
Solved Threads: 0
newtechie newtechie is offline Offline
Light Poster

word/line/character count in files

 
0
  #1
Aug 30th, 2008
i did a codig to find the no. of words,no. of characters and no. of lines in a file i was not getting the output, can anyone help me

import java.io.*;
public class countCharacters  
{
    public  void Lines()throws IOException
    {
        File f = new File("in.dat");
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
        String str = br.readLine();
                        
            LineNumberReader ln = new LineNumberReader(br);
            int count = 0;
            while (ln.readLine()!=null)
            {
                count++;
            }
            
            System.out.println("no. of lines in the file = " + count);
         
        }
         public  void Words()throws IOException
            // count no. of words.
         {
             File f = new File("in.dat");
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
             int index = 0;
            int numWords =0;
            boolean prevwhitespace = true;
                    String line = br.readLine();
            while(index < line.length())
            {
                char c = line.charAt(index++);
                boolean currwhitespace = Character.isWhitespace(c);
                if(prevwhitespace && !currwhitespace)
                {
                    numWords++;
                }
                prevwhitespace= currwhitespace;
            }
                    
                   System.out.println("no. of words in file" +numWords);
        }
         public  void Charact()throws IOException
                 // counting characters
         {
             File f = new File("in.dat");
             FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
               long numChar = f.length();
               int countChar =0;
               while(numChar !=-1)
               {
                   countChar++;
               }
               System.out.println("no. of characters in the file =" + countChar);
              //  return countChar;  
                
    }
         public static void main(String args[])throws IOException
     {
         countCharacters ob1 = new countCharacters();
           ob1.Charact();
           ob1.Words();
           ob1.Lines();
        
     }
}

the file input.dat is
<br />
java programming for internet<br />
 javascript for web page development<br />
pearl for server side scripting
Reply With Quote