src/share/classes/java/io/BufferedReader.java
Print this page
rev 7006 : 8003258: BufferedReader.lines()
Reviewed-by:
@@ -1,7 +1,7 @@
/*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
@@ -24,10 +24,17 @@
*/
package java.io;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+
/**
* Reads text from a character-input stream, buffering characters so as to
* provide for the efficient reading of characters, arrays, and lines.
*
* <p> The buffer size may be specified, or the default size may be used. The
@@ -520,6 +527,63 @@
in = null;
cb = null;
}
}
}
+
+ /**
+ * Returns a {@code Stream}, the elements of which are lines read from this
+ * {@code BufferedReader}. The {@link Stream} is lazily populated via
+ * calls to {@link #readLine()}.
+ *
+ * <p>Each element consumed by the {@code Stream} caused a line to be
+ * read from this {@code BufferedReader}. Since the {@code Stream} does
+ * not necessary consume all lines, it is possible to mix and use
+ * different read methods on a {@code BufferedReader}. Each method will
+ * simply pick up from where it was left on last read.
+ *
+ * <p>If an {@link IOException} is thrown when accessing the underlying
+ * {@code BufferedReader}, it is wrapped in an {@link
+ * UncheckedIOException} which will be thrown from the {@code Stream}
+ * method that caused the read to take place. For example, when trying to
+ * read from the {@code Stream} after the {@code BufferedReader} is
+ * closed, will throw an {@code UnchecheckedIOException}.
+ *
+ * @return a {@code Stream<String>} providing the lines of text
+ * described by this {@code BufferedReader}
+ *
+ * @since 1.8
+ */
+ public Stream<String> lines() {
+ Iterator<String> iter = new Iterator<String>() {
+ String nextLine = null;
+
+ @Override
+ public boolean hasNext() {
+ if (nextLine != null) {
+ return true;
+ } else {
+ try {
+ nextLine = readLine();
+ return (nextLine != null);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+ }
+
+ @Override
+ public String next() {
+ if (nextLine != null || hasNext()) {
+ try {
+ return nextLine;
+ } finally {
+ nextLine = null;
+ }
+ } else {
+ throw new NoSuchElementException();
+ }
+ }
+ };
+ return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED));
+ }
}