可以通过以下步骤实现:
File file = new File("文件路径");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
// 处理每一行的内容
}
HashMap<String, Integer> countMap = new HashMap<>();
String[] words = line.split("\\s+"); // 使用空格分割单词
for (String word : words) {
if (countMap.containsKey(word)) {
countMap.put(word, countMap.get(word) + 1);
} else {
countMap.put(word, 1);
}
}
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
String word = entry.getKey();
int count = entry.getValue();
System.out.println(word + ": " + count);
}
完整的代码示例:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class FileWordCount {
public static void main(String[] args) {
try {
File file = new File("文件路径");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
HashMap<String, Integer> countMap = new HashMap<>();
while ((line = bufferedReader.readLine()) != null) {
String[] words = line.split("\\s+");
for (String word : words) {
if (countMap.containsKey(word)) {
countMap.put(word, countMap.get(word) + 1);
} else {
countMap.put(word, 1);
}
}
}
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
String word = entry.getKey();
int count = entry.getValue();
System.out.println(word + ": " + count);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代码可以读取指定文件中的内容,并统计每个单词或字符出现的次数。请注意替换代码中的"文件路径"为实际的文件路径。
领取专属 10元无门槛券
手把手带您无忧上云