+92 332 4229 857 99ProjectIdeas@Gmail.com

Counting Lines And Characters In File (Java)




The following program takes input a character and matches in file and count the occurrences of that particular character and displays no. of times it found and also displays how many lines the file have.......










import java.io.*;

public class Test {

 public static void main(String[] args) {
             
  try {
                   
    BufferedReader br  = new BufferedReader(new InputStreamReader(System.in));

    System.out.print("Enter A Character To Find : ");

    String inputChar = br.readLine();
                   
    int lineCount = 0, charCount = 0;

    FileReader fr = new FileReader(new File("testFile.txt")) 

    BufferedReader br2 = new BufferedReader(fr);
                    
         String line = br2.readLine();
                    
          while ( line != null ) {
                          
              for (int i = 0 ; i < line.length(); i++) {
                                 
                    if (line.charAt(i) == inputChar.charAt(0)) {
                                 
                        charCount++;
                    }
                                 
              }
                                                     
              line = br2.readLine();
              lineCount++;
             
        }
                 
 System.out.println("File Contains " + lineCount + " lines");
 System.out.println("File Contains " + inputChar + " " + charCount + " times ");
                    
                          
    } catch (Exception e) {

    }
             
  }

}
      


0 comments: