如何在Java中将扫描仪字符串转换为Stream?

时间:2015-04-13 17:43:56

标签: java java-8 java-stream

Java8中,如何从扫描仪读取结果中形成Stream 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进行迭代的流。

2 个答案:

答案 0 :(得分:11)

你说这一切都错了,不需要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

答案 1 :(得分:1)

您根本不必创建Scanner。只需将资源作为URL

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