Saturday, 8 June 2013

count Space in a text file

Just have a counter variable initialize with '0'
Then start to read the file where the character is space increase the value of counter variable ...

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package filedemo;

/**
 *
 * @author Saeed
 */
import java .io.*;

public class ReadSpaces {
    public static void main(String args[])throws IOException {
        char ch;
            
                char space=' ';
                int count = 0;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                System.out.println("Enter the File Path Only");
        String path =br.readLine();
        String file_name = br.readLine();
        File f = new File(path+file_name);
        System.out.println("Press zero to end");   
        try (FileWriter fw = new FileWriter(f)) { // File Writer to Write Data inside File f
            do{
             ch=(char)br.read(); // to read data character by character
             fw.write(ch);//get data from console and write in FileWriter(File f)
             if (ch==space )
                     count++;
             }while(ch!='q');
           
    
        }catch(Exception e){
    System.err.println("Error: " + e.getMessage());    }
                System.out.println("You Enter the Spaces as "+count);
    }
}

No comments:

Post a Comment