如何在 Java 中将扫描器字符串制作成 Stream?

How to make scanner strings into a Stream in Java?

Java8中,如何从扫描器读取结果中形成Stream of String

InputStream is = A.class.getResourceAsStream("data.txt");
Scanner scanner = new Scanner(new BufferedInputStream(is), "UTF-8");
while (scanner.hasNextLine()) {
    System.out.println(scanner.nextLine());
}

这就是将扫描仪变成我想使用 forEach 进行迭代的流。

你的做法全错了,不需要 Scanner:

try (final InputStream is = A.class.getResourceAsStream("data.txt");
        final Reader r = new InputStreamReader(is, StandardCharsets.UTF_8);
        final BufferedReader br = new BufferedReader(r);
        final Stream<String> lines = br.lines()) {

}

如果你真的想使用 Scanner 那么它 implements Iterator 所以你可以这样做:

public Stream<String> streamScanner(final Scanner scanner) {
    final Spliterator<String> splt = Spliterators.spliterator(scanner, Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.NONNULL);
    return StreamSupport.stream(splt, false)
            .onClose(scanner::close);
}

P.S。您似乎也没有关闭资源。 总是关闭一个InputStream

您根本不必创建 Scanner。只是资源作为 URL.

URL url = A.class.getResource("data.txt");
Files.lines(Paths.get(url.getPath())).forEach(line -> {});