写一段java代码,读取.txt文件夹种内容,文本内容以逗号或者空格分隔成每个词语,随机出20个词语,要求20个词语不重复,并且一个字的词语不能出现
时间: 2024-05-07 08:23:51 浏览: 51
C++_C++_读取txt文档_txt内容读取_按空格分隔_按逗号分隔_
5星 · 资源好评率100%
```
import java.io.*;
import java.util.*;
public class RandomWords {
public static void main(String[] args) {
try {
// 读取文本文件内容
File file = new File("words.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
List<String> words = new ArrayList<>();
while ((line = reader.readLine()) != null) {
String[] tokens = line.split("[,\\s]+");
for (String token : tokens) {
if (token.length() > 1) {
words.add(token);
}
}
}
reader.close();
// 随机选择20个不重复的词语
Set<String> selectedWords = new HashSet<>();
Random random = new Random();
while (selectedWords.size() < 20) {
String word = words.get(random.nextInt(words.size()));
if (word.length() > 1) {
selectedWords.add(word);
}
}
// 输出结果
System.out.println("随机选择的20个词语:");
for (String word : selectedWords) {
System.out.println(word);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文