Count occurrences of characters in a file

1. Guide package

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

2. Code

public static void main(String[] args) throws Exception {
		
		//Create a map collection to store the character and the number of times the character appears
		Map<Character,Integer> map = new HashMap<Character,Integer>();
		//Create a character input buffer stream object, associated with the word.txt file
		BufferedReader br = new BufferedReader(new FileReader("word.txt"));
		//Create c to receive the characters read each time, the bottom layer will convert the read characters to int type by default
		int c;
		// read one character at a time
		while((c=br.read())!=-1) {
			
			// Convert to char type
			char ch = (char) c;
			//Get value according to key
			Integer value = map.get(ch);
			//If the value is empty, the character has not been stored
			if(value == null) {
				//Storage, the first storage, the value is 1
				map.put(ch, 1);
			}else {
				//Indicates that the value has been stored for times, as long as it is +1 on the basis of the value
				map.put(ch, value+1);
			}
		}
		
		// When the statistics are completed, print them out
		Set<Character> keys = map.keySet();
		for (Character key : keys) {
			Integer value = map.get(key);
			System.out.println(key+":"+value);
		}
	}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324478505&siteId=291194637