Java - 如何将具有特定长度的文本文件中的所有单词放入列表中

Java - how to put all words from a textfile with a specific length in a List

所以我有一个名为 wordlist.txt 的单词列表,我想将所有具有特定长度的单词(假设为 5)放入一个列表中。

首先,出于测试目的,我尝试将所有单词放入一个列表中,但是当我尝试 Files.exists 时出现错误 "Cannot resolve symbol 'exists'",它在 Main 函数中有效,但在class 出于某种原因。 Image Error

    ArrayList<String> list = new ArrayList<>();
private Path myFile = Paths.get("Resources/wordlist.txt");
if (Files.exists(myFile)){
    try (Scanner fileScanner = new Scanner(myFile)){
        while (fileScanner.hasNext()) {
            list.add(fileScanner.nextLine());
        }
    } catch (IOException ioe){
        System.out.println("The file doesn't exists!");
    }
}

我认为您需要像这样在路径中添加“/”:("/Resources/wordlist.txt"),因为您的项目的文件路径。

教程可以看here

首先,删除 private 修饰符 - 它不允许在方法内部。这应该可以解决您的语法错误。

其次,我建议您按照下面的简要示例说明文件夹结构:

src/main/java
 - Main.java  
src/main/resources
 - wordlist.txt

您已准备就绪,可以使用类加载器访问该文件。如果 Files.exists(myFile) returns 为真,则不会抛出 IOException。试试下面的代码:

ArrayList<String> list = new ArrayList<>();
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource("wordlist.txt").getFile());
try (Scanner fileScanner = new Scanner(file)) {
    while (fileScanner.hasNext()) {
        list.add(fileScanner.nextLine());
    }
} catch (IOException ioe) {
    System.out.println("The file doesn't exists!");
}

最后,问题的标签和你问的不符。我不确定我是否理解 "put all words" 正确。无论如何,我们建议文本文件每行包含一个单词,因此检查它的长度并决定是否添加到列表中。

while (fileScanner.hasNext()) {
    String line = fileScanner.nextLine();
    if (line.length() == 5) { // specific length, use a constant is better          
        list.add(line);
    }
}