7

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.

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Stephan Rozinsky
  • 553
  • 2
  • 6
  • 21

2 Answers2

15

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.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
3

You don't have to create a Scanner at all. Just the the resource as a URL.

URL url = A.class.getResource("data.txt");
Files.lines(Paths.get(url.getPath())).forEach(line -> {});
Bubletan
  • 3,833
  • 6
  • 25
  • 33