// 分析文本文件 private void analyzeFile() { String filename = textFile.getText().trim(); if (!filename.isEmpty()) { File file = new File(filename); if (file.exists() && file.isFile()) { try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line; while ((line = reader.readLine()) != null) { for (String word : wordMap.keySet()) { int count = 0; int pos = line.indexOf(word); while (pos != -1) { count++; pos = line.indexOf(word, pos + word.length()); } if (count > 0) { int oldCount = wordMap.get(word); wordMap.put(word, oldCount + count); } } }给每行代码后加上注释
时间: 2024-02-10 17:17:00 浏览: 26
// 分析文本文件
private void analyzeFile() {
// 获取文件名
String filename = textFile.getText().trim();
// 如果文件名不为空
if (!filename.isEmpty()) {
// 创建文件对象
File file = new File(filename);
// 如果文件存在且是一个普通文件
if (file.exists() && file.isFile()) {
// 创建 BufferedReader 对象
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
// 读取文件的每一行
String line;
while ((line = reader.readLine()) != null) {
// 遍历所有关键词
for (String word : wordMap.keySet()) {
// 统计关键词在当前行出现的次数
int count = 0;
int pos = line.indexOf(word);
while (pos != -1) {
count++;
pos = line.indexOf(word, pos + word.length());
}
// 如果关键词出现过
if (count > 0) {
// 更新关键词的计数
int oldCount = wordMap.get(word);
wordMap.put(word, oldCount + count);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这段代码的作用是分析一个指定的文本文件,统计其中各个关键词出现的次数,并更新 wordMap 中对应关键词的计数。具体实现过程是,先从文本框中获取文件名,然后创建一个文件对象,判断文件是否存在且是一个普通文件,如果是,则使用 BufferedReader 读取文件的每一行,遍历所有关键词,统计关键词在当前行出现的次数,如果关键词出现过,则更新关键词的计数。