只捕捉特定的字长

Only catch certain word lengths

如果我有一个名为 words.txt 的 .txt 文件,我想捕捉单词以将它们输入到数组列表中,我该怎么做。我知道缓冲 reader 存在,但我不太明白如何使用它。所有单词都由 space 或回车键分隔。例如,它必须过滤掉长度不是 4 个字符的单词,并将 4 个长单词放在数组列表中以备后用。 例如我得到了这个 txt 文件:

one > gets ignored
two > gets ignored
three > gets ignored
four >  caught and put into for example arraylist
five > 4 long so gets caught and put into arraylist
six > ignored
seven > ignored
eight >  ignored
nine >  caught because its 4 char long
ten > ignored

您可以使用 streams and NIO.2

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) {
        Path path = Paths.get("words.txt");
        try (Stream<String> lines = Files.lines(path)) {
            List<String> list = lines.filter(word -> word.length() == 4)
                                     .collect(Collectors.toList());
            System.out.println(list);
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}

这是我的 words.txt 文件:

one
two
three
four
five
six
seven
eight
nine
ten

和运行上面的代码,使用上面的文件,打印如下:

[four, five, nine]

或者,您可以使用 Scanner

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Path source = Paths.get("words.txt");
        try (Scanner scanner = new Scanner(source)) {
            List<String> list = new ArrayList<>();
            while (scanner.hasNextLine()) {
                String word = scanner.nextLine();
                if (word.length() == 4) {
                    list.add(word);
                }
            }
            System.out.println(list);
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}

请注意,以上两个版本的 class Main 使用 try-with-resources.

另一种方法是使用 class java.io.BufferedReader(因为您在问题中提到了它)。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        File f = new File("words.txt");
        try (FileReader fr = new FileReader(f);
             BufferedReader br = new BufferedReader(fr)) {
            List<String> list = new ArrayList<>();
            String line = br.readLine();
            while (line != null) {
                if (line.length() == 4) {
                    list.add(line);
                }
                line = br.readLine();
            }
            System.out.println(list);
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}