用java统计文件中单词个数
时间: 2023-11-12 09:06:34 浏览: 186
可以使用Java的文件读取和字符串处理功能来实现统计文件中单词个数的功能。具体实现步骤如下:
1. 首先需要读取文件中的所有内容。可以使用Java的File和Scanner类来实现。具体代码如下:
```java
File file = new File("文件路径");
Scanner scanner = new Scanner(file);
String content = "";
while (scanner.hasNextLine()) {
content += scanner.nextLine();
}
scanner.close();
```
2. 将读取到的内容按照空格进行分割,得到所有单词。可以使用Java的split方法来实现。具体代码如下:
```java
String[] words = content.split("\\s+");
```
3. 统计单词个数。可以使用Java的HashMap来实现。具体代码如下:
```java
Map<String, Integer> wordCountMap = new HashMap<>();
for (String word : words) {
if (wordCountMap.containsKey(word)) {
wordCountMap.put(word, wordCountMap.get(word) + 1);
} else {
wordCountMap.put(word, 1);
}
}
```
4. 输出结果。可以使用Java的System.out.println方法来输出结果。具体代码如下:
```java
for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
```
完整代码如下:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
File file = new File("文件路径");
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String content = "";
while (scanner.hasNextLine()) {
content += scanner.nextLine();
}
scanner.close();
String[] words = content.split("\\s+");
Map<String, Integer> wordCountMap = new HashMap<>();
for (String word : words) {
if (wordCountMap.containsKey(word)) {
wordCountMap.put(word, wordCountMap.get(word) + 1);
} else {
wordCountMap.put(word, 1);
}
}
for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
阅读全文
相关推荐















