Home Tutorial Java Io Count characters from text file in Java

 
 

Share on Google+Share on Google+
Count characters from text file in Java
Posted on: October 24, 2009 at 12:00 AM
Advertisement
In this section, you will learn how to count the occurrence of each character from the text file using Java Programming Language.

Count characters from text file Using Java

Here we are going to count the occurrence of each character from the text file. For this, we have used the BufferedReader  class to read the specified file. Then we have removed all the spaces between the string using replaceAll() method and then convert it into character array in order to count the occurrence of each character of the array. 

Here is the data.txt:

hello world
where there is a will there is a way

Here is the code:

import java.io.*;
import java.util.*;

class  CountCharactersFromFile {
  public static void main(String[] argsthrows Exception{
  FileInputStream fstream = new FileInputStream("C:\\data.txt");
     DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine="";
  String str="";
        while ((strLine = br.readLine()) != null)   {
       
    str+=strLine;
    }
   String st=str.replaceAll(" """);
   char[]third =st.toCharArray();
  System.out.println("Character     Total");
  for(int counter =0;counter<third.length;counter++){
  char ch= third[counter];
  int count=0;
  for int i=0; i<third.length; i++){
  if (ch==third[i])
  count++;
}
boolean flag=false;
for(int j=counter-1;j>=0;j--){
if(ch==third[j])
flag=true;
}
if(!flag){
System.out.println(ch+"                  "+count);
}
}
}

Output:

Character          Total
h                        4
e                        7
l                         5
o                        2
w                       4
r                         4
d                        1
t                         2
i                         3
s                        2
a                        3
y                        1
Advertisement

Related Tags for Count characters from text file in Java:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 24, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com