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[] args) throws 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 |
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.