Share on Google+Share on Google+

Count characters from text file in Java

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.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)   {
   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])
boolean flag=false;
for(int j=counter-1;j>=0;j--){
System.out.println(ch+"                  "+count);


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



Posted on: October 24, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.


Advertisement null