Java实现文本文件每行单词数统计及代码问题修复
问题原因
你的代码无法输出预期的单词统计结果,是3处逻辑错误导致的:
- 文件加载完成后没有调用单词统计方法,程序加载完文件就直接终止,不会执行统计逻辑
- 批量统计方法
CountWordsInDocuments写了自调用的无限递归逻辑,没有实际遍历文档集合的代码,一旦调用就会触发栈溢出错误 - 单文档统计方法
CountWordsInDocument中错误加入了遍历整个文档集合的代码,会触发重复递归,逻辑完全混乱
修改后完整代码
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.concurrent.ConcurrentHashMap; public class B1TextLoader { ConcurrentHashMap<String, String> documents = new ConcurrentHashMap<String, String>(); public static void main(String[] args) { B1TextLoader loader = new B1TextLoader(); loader.LoadTextFile("2-3-1BasicTextFile.txt"); } public void LoadTextFile(String filePath) { try { System.out.println("Loading file..."); File f = new File(filePath); BufferedReader br = new BufferedReader(new FileReader(f)); String line = br.readLine(); Integer counter = 0; while (line != null) { if (line.trim().length() > 0) { documents.put("doc" + counter, line); counter++; } line = br.readLine(); } br.close(); } catch (Exception e) { System.out.println("File Load Failed"); } System.out.println("Load Complete. Lines loaded: " + documents.size()); // 加载完成后调用批量统计方法 CountWordsInDocuments(documents); } public void CountWordsInDocuments(ConcurrentHashMap<String, String> documents) { // 遍历所有文档条目,调用单文档统计方法,删除原来的自调用递归逻辑 documents.forEach(this::CountWordsInDocument); } public void CountWordsInDocument(String key, String value) { String[] words = value.split(" "); System.out.println(key + " has " + words.length + " words!"); // 删除此处错误的遍历map代码,避免递归 } }
运行效果
使用你提供的测试文本运行代码,会输出完全符合预期的结果:
Loading file... Load Complete. Lines loaded: 5 doc0 has 6 words! doc1 has 8 words! doc2 has 4 words! doc3 has 4 words! doc4 has 6 words!
小提示:如果后续遇到行内有连续多个空格、行首尾有空格的场景,把切分规则从split(" ")改成split("\\s+"),统计结果会更准确,当前测试文本无这类特殊情况,原有切分规则可正常工作。
内容的提问来源于stack exchange,提问作者Bluetail
相关产品推荐
相关产品推荐

