Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make scanner strings into a Stream in Java? [duplicate]

In Java8, how can I form a Stream of String out of the scanner read results?

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

That is turn a scanner into a stream which I would like to iterate using forEach.

like image 831
Stephan Rozinsky Avatar asked Apr 13 '15 17:04

Stephan Rozinsky


1 Answers

You are going about this all wrong, no Scanner is required:

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()) {

}

If you really want to use a Scanner then it implements Iterator so you can just do:

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. you also don't seem to be closing resources. always close an InputStream.

like image 184
Boris the Spider Avatar answered Sep 21 '22 07:09

Boris the Spider