[代码] [Java]代码 import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.uti http://www.fpshijiazhuang.com/linked/20130225.do; l.Iterator;
import java.util.Map;
import java.util.Set;
public class CharactersUtils {
/**
* 获取文档中呈现的最多字符及数量
* @param path 文档途径。txt
* @return 最多的字符,key为字符,value为数量
*/
public static Map maxCountOfCharacters(String path) {
if (path == null) {
throw new NullPointerException("path");
}
Map characterCounts = getCharactersCount(path);
if (characterCounts == null) {
return null;
}
Set keys = characterCounts.keySet();
Iterator iterator = keys.iterator();
int max = 0;
Map result = new HashMap();
while (iterator.hasNext()) {
char currChar = iterator.next();
int currCount = characterCounts.get(currChar);
if (currCount > max) {
max = currCount;
result.clear();
result.put(currChar, max);
} else if (currCount == max) {
result.put(currChar, max);
}
}
return result;
}
/**
* 计算各个字符的数量
* @param path 文档途径
* @return 各个字符个数的map key为字符,value为数量
*/
private static Map getCharactersCount(String path) {
File file = null;
BufferedReader reader = null;
Map characterCounts = null;
try {
file = new File(path);
reader = new BufferedReader(new FileReader(file));
String temp = "";
characterCounts = new HashMap();
while ((temp = reader.readLine()) != null) {
if (temp.trim() != "") {
char[] chs = temp.trim().toCharArray();
for (char ch : chs) {
if (characterCounts.containsKey(ch)) {
characterCounts.put(ch, characterCounts.get(ch) 1);
} else {
characterCounts.put(ch, 1);
}
}
}
}
return characterCounts;
} catch (FileNotFoundException e) {
throw new RuntimeException("CharactersUtils:", e);
} catch (IOException e) {
throw new RuntimeException("CharactersUtils:", e);
}
}
} http://jy.aaafaipiao.com/linked/20130225.do;