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
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With