/**
* 有编码要求,必须和项目的编码格式相同
* 文件中指定字符的数量
* @param filename
* @param ch
* @return
*/
public static int charCount(String filename,char ch){
File file = new File(filename);
if (!file.exists()) {
System.out.println("文件不存在");
return 0;
}
int count = 0;
try {
FileReader fileReader = new FileReader(file);
int i = -1;
while ((i = fileReader.read()) != -1) {
if (ch == i) {
count++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(count);
return count;
}
/**
* 文件编码最好是UTF-8格式
* 文件中各个字符的数量
* @param filename
* @return
*/
public static Map<String,Integer> codeCount(String filename){
File file = new File(filename);
if (!file.exists()) {
System.out.println("文件不存在");
return null;
}
ConcurrentHashMap<String, Integer> countMap = new ConcurrentHashMap<String, Integer>();
FileReader fileReader = null;
try {
fileReader = new FileReader(file);
int i = -1;
while ((i = fileReader.read()) != -1) {
char ch = (char)i;
if(ch == '\r' || ch == '\n'){
continue;
}
String key = String.valueOf(ch);
if(countMap.keySet().contains(key)){
countMap.put(key,countMap.get(key)+1);
}else{
countMap.put(key, 1);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return countMap;
}
文件中字符统计
最新推荐文章于 2020-06-04 17:06:49 发布