A class for reading lines of text. Provides the same functionality as java.io.BufferedReader#readLine() but for all Readable objects, not just instances of Reader. @author Chris Nokleberg @since 1.0
| 36 | * @since 1.0 |
| 37 | */ |
| 38 | @Beta |
| 39 | @GwtIncompatible |
| 40 | public final class LineReader { |
| 41 | private final Readable readable; |
| 42 | private final Reader reader; |
| 43 | private final CharBuffer cbuf = createBuffer(); |
| 44 | private final char[] buf = cbuf.array(); |
| 45 | |
| 46 | private final Queue<String> lines = new LinkedList<String>(); |
| 47 | private final LineBuffer lineBuf = |
| 48 | new LineBuffer() { |
| 49 | @Override |
| 50 | protected void handleLine(String line, String end) { |
| 51 | lines.add(line); |
| 52 | } |
| 53 | }; |
| 54 | |
| 55 | /** |
| 56 | * Creates a new instance that will read lines from the given {@code Readable} object. |
| 57 | */ |
| 58 | public LineReader(Readable readable) { |
| 59 | this.readable = checkNotNull(readable); |
| 60 | this.reader = (readable instanceof Reader) ? (Reader) readable : null; |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Reads a line of text. A line is considered to be terminated by any one of a line feed |
| 65 | * ({@code '\n'}), a carriage return ({@code '\r'}), or a carriage return followed immediately by |
| 66 | * a linefeed ({@code "\r\n"}). |
| 67 | * |
| 68 | * @return a {@code String} containing the contents of the line, not including any |
| 69 | * line-termination characters, or {@code null} if the end of the stream has been reached. |
| 70 | * @throws IOException if an I/O error occurs |
| 71 | */ |
| 72 | @CanIgnoreReturnValue // to skip a line |
| 73 | public String readLine() throws IOException { |
| 74 | while (lines.peek() == null) { |
| 75 | cbuf.clear(); |
| 76 | // The default implementation of Reader#read(CharBuffer) allocates a |
| 77 | // temporary char[], so we call Reader#read(char[], int, int) instead. |
| 78 | int read = (reader != null) |
| 79 | ? reader.read(buf, 0, buf.length) |
| 80 | : readable.read(cbuf); |
| 81 | if (read == -1) { |
| 82 | lineBuf.finish(); |
| 83 | break; |
| 84 | } |
| 85 | lineBuf.add(buf, 0, read); |
| 86 | } |
| 87 | return lines.poll(); |
| 88 | } |
| 89 | } |
nothing calls this directly
no test coverage detected