关键的地方就是用到了Java中的IO流的操作,将文件写到缓冲区里面,然后利用map的特性储存元素的键和值
import java.io.*;
import java.util.*;
public class Count_Demo {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
countFile(new File("));
long endTime = System.currentTimeMillis();
System.out.println("n运行时间:" + (endTime - startTime) + "毫秒");
}
/**
*
* @param file
*/
public static void countFile(File file){
BufferedReader bfr = null; //定义字符读取(缓冲)流
try{
bfr = new BufferedReader(new FileReader(file));//给该流赋值
String value = null; //定义一个临时接收文件中的字符串变量
String newValue = ""; //接收文件中所有字符串的变量
while((value = adLine()) != null){ //开始读取文件中的字符
newValue = newValue + LowerCase(); //存入newValue变量中,全部转换成小写方便合并统计
}
int i = newValue.length();
char[] ch = CharArray();//把newValue变成字符数组
TreeMap map = new TreeMap(); //定义一个TreeMap,默认从小到大顺序,键对应字符,值对应字符出现的次数
for(int x = 0;x < ch.length; x++){ //遍历ch,将ch中所有的字符存入一个Map集合中(TreeSet),键对应字符,值对应字符出现的次数
char c = ch[x];
if(!ainsKey(c)){
map.put(c, 1);
}
else{
int count = (c);
map.put(c, count + 1);
}
}
//下面的是取出TreeMap(map)中的键和值
Set> set = Set();
Iterator> iter = set.iterator();
while(iter.hasNext()){
Map.Entry maps = ();
char k = Key();
int v = Value();
System.out.println("字母: "+ k + " 在文章中出现了(" + v + "次) ");
}
}
catch(IOException e){
}
finally{
try{
if(bfr!=null)
bfr.close();
}
catch(IOException e){
}
}
}
}
本文发布于:2024-02-01 18:04:52,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170678220838488.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |