我试图理解如何将文件的每个单词放入HashSet中。我正在编写的方法应该读取文件并将文件中的单词作为 HashSet 返回。我还必须使用方法split((,但不知道如何使用它。我还有一个 normalize(( 方法,可以将所有单词转换为小写。这就是我走多远:
public static HashSet<String> extractWordsFromDocument(String filename) {
try {
FileReader in = new FileReader(filename);
Scanner file = new Scanner(in);
while(file.hasNext( )){
try {
String line = file.nextLine();
line = line.normalize();
line = line.split();
Set<String> words = new HashSet<String>();
hashset.add(line);
System.out.println(words);
}
catch (Exception e) {
}
}
}
catch (FileNotFoundException e) {
System.out.println("Working Directory = " + System.getProperty("user.dir"));
}
return null;
}
我知道这段代码中有很多错误。我只是一个初学者...
您正在循环中创建HashSet
,这意味着文件中的每一行都有一个新,并且每行将仅包含该行中的单词。
此外,您可以更好地利用 Scanner
,它有一个next()
方法,将为您提供由空格(空格、制表符、行尾等(分隔的单词,这是默认的分隔符。
并记得关闭您的资源。从 Java 7 开始,您可以使用 try-with-resources 语句。
另外,不要吞下你的例外。
public static Set<String> extractWordsFromDocument(String filename) throws IOException {
try (Reader in = new FileReader(filename)) {
Set<String> words = new HashSet<>();
Scanner scanner = new Scanner(in);
while (scanner.hasNext()){
words.add(scanner.next());
}
return words;
}
}
如果您想知道String
或split()
的工作原理,请阅读文档...