Share on Google+Share on Google+

Java count characters from file

Advertisement
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

Advertisements

Posted on: August 1, 2006 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.