包含path和files,try和catch,以及static String readFiles的英文文本单词统计的JAVA的代码怎么写
时间: 2023-06-08 20:04:40 浏览: 85
单词java写的代码
以下是一个包含path和files,try和catch,以及static String readFiles的JAVA代码,用于对英文文本的单词统计:
import java.io.*;
import java.util.*;
public class WordCount {
public static void main(String[] args) {
String fileName = "input.txt"; // 要统计的文件名
String filePath = "D:/documents/"; // 文件路径
String fullPath = filePath + fileName; // 拼接成完整的路径
HashMap<String, Integer> wordCountMap = new HashMap<>(); // 用于存放单词计数的Map
try {
File file = new File(fullPath);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = "";
while ((line = bufferedReader.readLine()) != null) {
String[] words = line.split("\\s+"); // 根据空格分割每行文本
for (String word : words) {
String normalizedWord = word.replaceAll("\\pP|\\pS", ""); // 将标点符号去除
if (!normalizedWord.isEmpty()) { // 如果单词不为空
wordCountMap.put(normalizedWord, wordCountMap.getOrDefault(normalizedWord, 0) + 1); // 将单词计数放入Map中
}
}
}
bufferedReader.close();
fileReader.close();
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
// 输出单词计数
for (String word : wordCountMap.keySet()) {
System.out.println(word + ": " + wordCountMap.get(word));
}
}
// 读取指定路径下的文件内容为字符串
private static String readFiles(String filePath, String fileName) throws IOException {
String fullPath = filePath + fileName; // 拼接成完整的路径
File file = new File(fullPath);
StringBuilder stringBuilder = new StringBuilder();
try (FileReader fileReader = new FileReader(file)) {
char[] buffer = new char[1024]; // 缓存
int length;
while ((length = fileReader.read(buffer)) != -1) {
stringBuilder.append(buffer, 0, length); // 将读取的字符放入StringBuilder中
}
}
return stringBuilder.toString();
}
}
希望这能帮到你!
阅读全文