Path: blob/master/src/java.base/share/classes/java/io/LineNumberReader.java
41152 views
/*1* Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.io;2627/**28* A buffered character-input stream that keeps track of line numbers. This29* class defines methods {@link #setLineNumber(int)} and {@link30* #getLineNumber()} for setting and getting the current line number31* respectively.32*33* <p> By default, line numbering begins at 0. This number increments at every34* <a href="#lt">line terminator</a> as the data is read, and at the end of the35* stream if the last character in the stream is not a line terminator. This36* number can be changed with a call to {@code setLineNumber(int)}. Note37* however, that {@code setLineNumber(int)} does not actually change the current38* position in the stream; it only changes the value that will be returned by39* {@code getLineNumber()}.40*41* <p> A line is considered to be <a id="lt">terminated</a> by any one of a42* line feed ('\n'), a carriage return ('\r'), or a carriage return followed43* immediately by a linefeed, or any of the previous terminators followed by44* end of stream, or end of stream not preceded by another terminator.45*46* @author Mark Reinhold47* @since 1.148*/4950public class LineNumberReader extends BufferedReader {5152/** Previous character types */53private static final int NONE = 0; // no previous character54private static final int CHAR = 1; // non-line terminator55private static final int EOL = 2; // line terminator56private static final int EOF = 3; // end-of-file5758/** The previous character type */59private int prevChar = NONE;6061/** The current line number */62private int lineNumber = 0;6364/** The line number of the mark, if any */65private int markedLineNumber; // Defaults to 06667/** If the next character is a line feed, skip it */68private boolean skipLF;6970/** The skipLF flag when the mark was set */71private boolean markedSkipLF;7273/**74* Create a new line-numbering reader, using the default input-buffer75* size.76*77* @param in78* A Reader object to provide the underlying stream79*/80public LineNumberReader(Reader in) {81super(in);82}8384/**85* Create a new line-numbering reader, reading characters into a buffer of86* the given size.87*88* @param in89* A Reader object to provide the underlying stream90*91* @param sz92* An int specifying the size of the buffer93*/94public LineNumberReader(Reader in, int sz) {95super(in, sz);96}9798/**99* Set the current line number.100*101* @param lineNumber102* An int specifying the line number103*104* @see #getLineNumber105*/106public void setLineNumber(int lineNumber) {107this.lineNumber = lineNumber;108}109110/**111* Get the current line number.112*113* @return The current line number114*115* @see #setLineNumber116*/117public int getLineNumber() {118return lineNumber;119}120121/**122* Read a single character. <a href="#lt">Line terminators</a> are123* compressed into single newline ('\n') characters. The current line124* number is incremented whenever a line terminator is read, or when the125* end of the stream is reached and the last character in the stream is126* not a line terminator.127*128* @return The character read, or -1 if the end of the stream has been129* reached130*131* @throws IOException132* If an I/O error occurs133*/134@SuppressWarnings("fallthrough")135public int read() throws IOException {136synchronized (lock) {137int c = super.read();138if (skipLF) {139if (c == '\n')140c = super.read();141skipLF = false;142}143switch (c) {144case '\r':145skipLF = true;146case '\n': /* Fall through */147lineNumber++;148prevChar = EOL;149return '\n';150case -1:151if (prevChar == CHAR)152lineNumber++;153prevChar = EOF;154break;155default:156prevChar = CHAR;157break;158}159return c;160}161}162163/**164* Reads characters into a portion of an array. This method will block165* until some input is available, an I/O error occurs, or the end of the166* stream is reached.167*168* <p> If {@code len} is zero, then no characters are read and {@code 0} is169* returned; otherwise, there is an attempt to read at least one character.170* If no character is available because the stream is at its end, the value171* {@code -1} is returned; otherwise, at least one character is read and172* stored into {@code cbuf}.173*174* <p><a href="#lt">Line terminators</a> are compressed into single newline175* ('\n') characters. The current line number is incremented whenever a176* line terminator is read, or when the end of the stream is reached and177* the last character in the stream is not a line terminator.178*179* @param cbuf {@inheritDoc}180* @param off {@inheritDoc}181* @param len {@inheritDoc}182*183* @return {@inheritDoc}184*185* @throws IndexOutOfBoundsException {@inheritDoc}186* @throws IOException {@inheritDoc}187*/188@SuppressWarnings("fallthrough")189public int read(char cbuf[], int off, int len) throws IOException {190synchronized (lock) {191int n = super.read(cbuf, off, len);192193if (n == -1) {194if (prevChar == CHAR)195lineNumber++;196prevChar = EOF;197return -1;198}199200for (int i = off; i < off + n; i++) {201int c = cbuf[i];202if (skipLF) {203skipLF = false;204if (c == '\n')205continue;206}207switch (c) {208case '\r':209skipLF = true;210case '\n': /* Fall through */211lineNumber++;212break;213}214}215216if (n > 0) {217switch ((int)cbuf[off + n - 1]) {218case '\r':219case '\n': /* Fall through */220prevChar = EOL;221break;222default:223prevChar = CHAR;224break;225}226}227228return n;229}230}231232/**233* Read a line of text. <a href="#lt">Line terminators</a> are compressed234* into single newline ('\n') characters. The current line number is235* incremented whenever a line terminator is read, or when the end of the236* stream is reached and the last character in the stream is not a line237* terminator.238*239* @return A String containing the contents of the line, not including240* any <a href="#lt">line termination characters</a>, or241* {@code null} if the end of the stream has been reached242*243* @throws IOException244* If an I/O error occurs245*/246public String readLine() throws IOException {247synchronized (lock) {248boolean[] term = new boolean[1];249String l = super.readLine(skipLF, term);250skipLF = false;251if (l != null) {252lineNumber++;253prevChar = term[0] ? EOL : EOF;254} else { // l == null255if (prevChar == CHAR)256lineNumber++;257prevChar = EOF;258}259return l;260}261}262263/** Maximum skip-buffer size */264private static final int maxSkipBufferSize = 8192;265266/** Skip buffer, null until allocated */267private char skipBuffer[] = null;268269/**270* {@inheritDoc}271*/272public long skip(long n) throws IOException {273if (n < 0)274throw new IllegalArgumentException("skip() value is negative");275int nn = (int) Math.min(n, maxSkipBufferSize);276synchronized (lock) {277if ((skipBuffer == null) || (skipBuffer.length < nn))278skipBuffer = new char[nn];279long r = n;280while (r > 0) {281int nc = read(skipBuffer, 0, (int) Math.min(r, nn));282if (nc == -1)283break;284r -= nc;285}286if (n - r > 0) {287prevChar = NONE;288}289return n - r;290}291}292293/**294* Mark the present position in the stream. Subsequent calls to reset()295* will attempt to reposition the stream to this point, and will also reset296* the line number appropriately.297*298* @param readAheadLimit299* Limit on the number of characters that may be read while still300* preserving the mark. After reading this many characters,301* attempting to reset the stream may fail.302*303* @throws IOException304* If an I/O error occurs305*/306public void mark(int readAheadLimit) throws IOException {307synchronized (lock) {308// If the most recently read character is '\r', then increment the309// read ahead limit as in this case if the next character is '\n',310// two characters would actually be read by the next read().311if (skipLF)312readAheadLimit++;313super.mark(readAheadLimit);314markedLineNumber = lineNumber;315markedSkipLF = skipLF;316}317}318319/**320* Reset the stream to the most recent mark.321*322* @throws IOException323* If the stream has not been marked, or if the mark has been324* invalidated325*/326public void reset() throws IOException {327synchronized (lock) {328super.reset();329lineNumber = markedLineNumber;330skipLF = markedSkipLF;331}332}333334}335336337