使用扫描仪创建单词流

时间:2018-11-19 21:43:16

标签: java loops java-stream builder word

需要从文件中返回包含3个字母或更多字母的所有单词的流。有没有更好的方法,然后可以使用Stream.iterate:

private Stream<String> getWordsStream(String path){
    Stream.Builder<String> wordsStream = Stream.builder();
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(path);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Scanner s = new Scanner(inputStream);
    s.useDelimiter("([^a-zA-Z])");
    Pattern pattern = Pattern.compile("([a-zA-Z]{3,})");
    while ((s.hasNext())){
        if(s.hasNext(pattern)){
            wordsStream.add(s.next().toUpperCase());
        }
        else {
            s.next();
        }
    }
    s.close();
    return wordsStream.build();
}

3 个答案:

答案 0 :(得分:5)

代码最糟糕的部分是以下部分

FileInputStream inputStream = null;
try {
    inputStream = new FileInputStream(path);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
Scanner s = new Scanner(inputStream);

因此,当文件不存在时,将打印FileNotFoundException堆栈跟踪,并继续进行null输入流,从而导致NullPointerException。您应该在方法签名中声明NullPointerException,而不是要求调用者处理虚假的FileNotFoundException。否则,在错误的情况下返回空流。

但是您根本不需要构造FileInputStream,因为Scanner提供了接受FilePath的构造函数。将其与返回匹配流(自Java 9起)的功能结合在一起,您将得到:

private Stream<String> getWordsStream(String path) {
    try {
        Scanner s = new Scanner(Paths.get(path));
        return s.findAll("([a-zA-Z]{3,})").map(mr -> mr.group().toUpperCase());
    } catch(IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        return Stream.empty();
    }
}

或最好

private Stream<String> getWordsStream(String path) throws IOException {
    Scanner s = new Scanner(Paths.get(path));
    return s.findAll("([a-zA-Z]{3,})").map(mr -> mr.group().toUpperCase());
}

您甚至不需要在这里.useDelimiter("([^a-zA-Z])"),因为跳过所有不匹配的内容是默认行为。

关闭返回的Stream也会关闭Scanner

所以呼叫者应该这样使用

try(Stream<String> s = getWordsStream("path/to/file")) {
    s.forEach(System.out::println);
}

答案 1 :(得分:2)

您可以使用Files.lines()Pattern

private static final Pattern SPACES = Pattern.compile("[^a-zA-Z]+");

public static Stream<String> getWordStream(String path) throws IOException{
    return Files.lines(Paths.get(path))
        .flatMap(SPACES::splitAsStream)
        .filter(word -> word.length() >= 3);
}

答案 2 :(得分:0)

这是更简单的方法:从文件到Stream读取行,并以所需条件(例如,长度> = 3)对其进行过滤。 Files.lines()具有延迟加载功能,因此它不会在一开始就准备好文件中的所有单词,而是在每次需要下一个单词时都准备就绪

public static void main(String... args) throws IOException {
    getWordsStream(Paths.get("d:/words.txt")).forEach(System.out::println);
}

public static Stream<String> getWordsStream(Path path) throws IOException {
    final Scanner scan = new Scanner(path);

    return StreamSupport.stream(new Spliterators.AbstractSpliterator<String>(Long.MAX_VALUE,
            Spliterator.DISTINCT | Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.ORDERED) {
        @Override
        public boolean tryAdvance(Consumer<? super String> action) {
            while (scan.hasNext()) {
                String word = scan.next();

                // you can use RegExp if you have more complicated condition
                if (word.length() < 3)
                    continue;

                action.accept(word);
                return true;
            }

            return false;
        }
    }, false).onClose(scan::close);
}