10.26

发布时间 2023-11-13 21:02:02作者: new菜鸟

今天对文件处理与流文件进行了学习

package com.example.demo3;
import java.io.*;
import java.util.*;
public class HelloApplication {
public static void main(String[] args) {
// 读取txt文件
String filePath = "C:\\Users\\lenovo\\Desktop\\哈利波特英文版\\Harry Potter and the Goblet of Fire.txt";
String outputFilePath = "2.txt";

try {
// 创建BufferedReader对象读取文件内容
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
Map<String, Integer> wordCountMap = new HashMap<>();

// 逐行读取文件内容并统计单词出现次数
while ((line = reader.readLine()) != null) {
String[] words = line.split("\\s+");

for (String word : words) {
if (!word.isEmpty()) {
wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
}
}
}


PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>((a, b) ->
b.getValue().compareTo(a.getValue()));

for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {
pq.offer(entry);
}
Scanner scanner = new Scanner(System.in);
System.out.print("请输入前N个单词的数量:");
int n = scanner.nextInt();
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath));
for (int i = 0; i < n && !pq.isEmpty(); i++) {
Map.Entry<String, Integer> entry = pq.poll();
String word = entry.getKey();
int count = entry.getValue();
System.out.println("Word: " + word + ", Count: " + count);
writer.write("Word: " + word + ", Count: " + count);
writer.newLine();
}
writer.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
并进行了javaweb的增删改查的学习