Home Tutorial Java Core Files Java count characters from file

 
 

Java count characters from file
Posted on: August 1, 2006 at 12:00 AM
In this section, you will learn how to count characters from the file.<

Java count characters from file

In this section, you will learn how to count characters from the file.

Description of code:

Firstly, we have used FileReader and BufferedReader class to read the file 'data.txt' and stored the data into string. Then we have removed all the spaces between the string using replaceAll() method and convert the string to lowercase. This string is then converted into character array in order to count the occurrence of each character of the array. 

Here is the data.txt:

Hello

All glitters are not gold

Here is the code:

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

class CountCharactersFromFile {
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new FileReader("C:/data.txt"));
		String strLine = "";
		String str = "";
		while ((strLine = br.readLine()) != null) {
			str += strLine;
		}
		String st = str.replaceAll(" ", "").toLowerCase();
		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);
			}
		}
	}
}

Through the above code, you can read the file and count the occurrence of each character of the content of the file.

Output:

Character     Total
h                        1
e                        3
l                         6
o                        3
a                        2
g                        2
i                         1
t                         3
r                         2
s                        1
n                        1
d                        1

Related Tags for Java count characters from file:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.