题目
- 将上面歌词内容存放到本地磁盘D 根目录,文件命名为
word.txt
- 选择合适的IO流读取word.txt文件的内容
- 统计每个单词出现的次数(单词忽略大小写)
- 如果出现组合单词如
you're
按一个单词处理 将统计的结果存储到本地磁盘D根目录下的
wordcount.txt
文件
wordcount.txt每行数据个数如下and 10个 konw 20个
public class Homework {
public static void main(String[] args) {
try(FileInputStream fis = new FileInputStream("word.txt");
FileOutputStream fos = new FileOutputStream("wordcount.txt")) {
//定义字节数组存储读取到的内容
byte[] bytes = new byte[1024];//一次读取1KB
//因为文件的内容可能大于1KB,所以我们需要循环读取多次
StringBuilder sb = new StringBuilder();//用于存放获取到的所有内容
while (fis.read(bytes) != -1) {
sb.append(new String(bytes));
}
String content = sb.toString();
//替换掉sb里的换行符
content = content.replace("\r", " ");
content = content.replace("\n", " ");
content = content.replace("\r\n", " ");
//把内容转成小写
content = content.toLowerCase();
//按空格切分字符串
String[] contents = content.split(" ");
HashMap<String, Integer> map = new HashMap<>();//用于统计每个单词出现的次数
for (String word : contents) {
if (map.containsKey(word)) {//如果key相同,取出value,让其加1,然后再存回去
map.put(word, map.get(word) + 1);
} else {
map.put(word, 1);
}
}
//把map的内容写到文件wordcount.txt里,每个key-value存做一行
//遍历map
for (Map.Entry<String,Integer> entry : map.entrySet()) {
fos.write((entry.getKey() + " " + entry.getValue() + "个\n").getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
评论 (0)