2 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
3 Free Software Foundation, Inc.
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
42 /* Written using "Java Class Libraries", 2nd edition, plus online
43 * API docs for JDK 1.2 beta from http://www.javasoft.com.
44 * Status: Believed complete and correct.
48 * This subclass of <code>FilterReader</code> buffers input from an
49 * underlying implementation to provide a possibly more efficient read
50 * mechanism. It maintains the buffer and buffer state in instance
51 * variables that are available to subclasses. The default buffer size
52 * of 8192 chars can be overridden by the creator of the stream.
54 * This class also implements mark/reset functionality. It is capable
55 * of remembering any number of input chars, to the limits of
56 * system memory or the size of <code>Integer.MAX_VALUE</code>
58 * @author Per Bothner <bothner@cygnus.com>
59 * @author Aaron M. Renn <arenn@urbanophile.com>
61 public class BufferedReader extends Reader
65 /* Index of current read position. Must be >= 0 and <= limit. */
66 /* There is a special case where pos may be equal to limit+1; this
67 * is used as an indicator that a readLine was done with a '\r' was
68 * the very last char in the buffer. Since we don't want to read-ahead
69 * and potentially block, we set pos this way to indicate the situation
70 * and deal with it later. Doing it this way rather than having a
71 * separate boolean field to indicate the condition has the advantage
72 * that it is self-clearing on things like mark/reset.
75 /* Limit of valid data in buffer. Must be >= pos and <= buffer.length. */
76 /* This can be < pos in the one special case described above. */
79 /* The value -1 means there is no mark, or the mark has been invalidated.
80 Otherwise, markPos is the index in the buffer of the marked position.
81 Must be >= 0 and <= pos.
82 Note we do not explicitly store the read-limit.
83 The implicit read-limit is (buffer.length - markPos), which is
84 guaranteed to be >= the read-limit requested in the call to mark. */
87 // The JCL book specifies the default buffer size as 8K characters.
88 // This is package-private because it is used by LineNumberReader.
89 static final int DEFAULT_BUFFER_SIZE = 8192;
92 * Create a new <code>BufferedReader</code> that will read from the
93 * specified subordinate stream with a default buffer size of 8192 chars.
95 * @param in The subordinate stream to read from
97 public BufferedReader(Reader in)
99 this(in, DEFAULT_BUFFER_SIZE);
103 * Create a new <code>BufferedReader</code> that will read from the
104 * specified subordinate stream with a buffer size that is specified by the
107 * @param in The subordinate stream to read from
108 * @param size The buffer size to use
110 public BufferedReader(Reader in, int size)
114 buffer = new char[size];
118 * This method closes the underlying stream and frees any associated
121 * @exception IOException If an error occurs
123 public void close() throws IOException
135 * Returns <code>true</code> to indicate that this class supports mark/reset
138 * @return <code>true</code>
140 public boolean markSupported()
146 * Mark a position in the input to which the stream can be
147 * "reset" by calling the <code>reset()</code> method. The parameter
148 * <code>readLimit</code> is the number of chars that can be read from the
149 * stream after setting the mark before the mark becomes invalid. For
150 * example, if <code>mark()</code> is called with a read limit of 10, then
151 * when 11 chars of data are read from the stream before the
152 * <code>reset()</code> method is called, then the mark is invalid and the
153 * stream object instance is not required to remember the mark.
155 * Note that the number of chars that can be remembered by this method
156 * can be greater than the size of the internal read buffer. It is also
157 * not dependent on the subordinate stream supporting mark/reset
160 * @param readLimit The number of chars that can be read before the mark
163 * @exception IOException If an error occurs
165 public void mark(int readLimit) throws IOException
170 // In this method we need to be aware of the special case where
171 // pos + 1 == limit. This indicates that a '\r' was the last char
172 // in the buffer during a readLine. We'll want to maintain that
173 // condition after we shift things around and if a larger buffer is
174 // needed to track readLimit, we'll have to make it one element
175 // larger to ensure we don't invalidate the mark too early, if the
176 // char following the '\r' is NOT a '\n'. This is ok because, per
177 // the spec, we are not required to invalidate when passing readLimit.
179 // Note that if 'pos > limit', then doing 'limit -= pos' will cause
180 // limit to be negative. This is the only way limit will be < 0.
182 if (pos + readLimit > limit)
184 char[] old_buffer = buffer;
185 int extraBuffSpace = 0;
188 if (readLimit + extraBuffSpace > limit)
189 buffer = new char[readLimit + extraBuffSpace];
193 System.arraycopy(old_buffer, pos, buffer, 0, limit);
200 // Maintain the relationship of 'pos > limit'.
206 // Now pos + readLimit <= buffer.length. thus if we need to read
207 // beyond buffer.length, then we are allowed to invalidate markPos.
212 * Reset the stream to the point where the <code>mark()</code> method
213 * was called. Any chars that were read after the mark point was set will
214 * be re-read during subsequent reads.
216 * This method will throw an IOException if the number of chars read from
217 * the stream since the call to <code>mark()</code> exceeds the mark limit
218 * passed when establishing the mark.
220 * @exception IOException If an error occurs;
222 public void reset() throws IOException
228 throw new IOException("mark never set or invalidated");
230 // Need to handle the extremely unlikely case where a readLine was
231 // done with a '\r' as the last char in the buffer; which was then
232 // immediately followed by a mark and a reset with NO intervening
233 // read of any sort. In that case, setting pos to markPos would
234 // lose that info and a subsequent read would thus not skip a '\n'
235 // (if one exists). The value of limit in this rare case is zero.
236 // We can assume that if limit is zero for other reasons, then
237 // pos is already set to zero and doesn't need to be readjusted.
244 * This method determines whether or not a stream is ready to be read. If
245 * this method returns <code>false</code> then this stream could (but is
246 * not guaranteed to) block on the next read attempt.
248 * @return <code>true</code> if this stream is ready to be read,
249 * <code>false</code> otherwise
251 * @exception IOException If an error occurs
253 public boolean ready() throws IOException
258 return pos < limit || in.ready();
263 * This method read chars from a stream and stores them into a caller
264 * supplied buffer. It starts storing the data at index
265 * <code>offset</code> into
266 * the buffer and attempts to read <code>len</code> chars. This method can
267 * return before reading the number of chars requested. The actual number
268 * of chars read is returned as an int. A -1 is returned to indicate the
271 * This method will block until some data can be read.
273 * @param buf The array into which the chars read should be stored
274 * @param offset The offset into the array to start storing chars
275 * @param count The requested number of chars to read
277 * @return The actual number of chars read, or -1 if end of stream.
279 * @exception IOException If an error occurs.
281 public int read(char[] buf, int offset, int count) throws IOException
286 // Once again, we need to handle the special case of a readLine
287 // that has a '\r' at the end of the buffer. In this case, we'll
288 // need to skip a '\n' if it is the next char to be read.
289 // This special case is indicated by 'pos > limit'.
290 boolean retAtEndOfBuffer = false;
292 int avail = limit - pos;
299 if (limit == buffer.length)
300 markPos = -1; // read too far - invalidate the mark.
303 // Set a boolean and make pos == limit to simplify things.
304 retAtEndOfBuffer = true;
309 // Optimization: can read directly into buf.
310 if (count >= buffer.length && !retAtEndOfBuffer)
311 return in.read(buf, offset, count);
314 avail = in.read(buffer, limit, buffer.length - limit);
315 if (retAtEndOfBuffer && avail > 0 && buffer[limit] == '\n')
329 System.arraycopy(buffer, pos, buf, offset, count);
335 /* Read more data into the buffer. Update pos and limit appropriately.
336 Assumes pos==limit initially. May invalidate the mark if read too much.
337 Return number of chars read (never 0), or -1 on eof. */
338 private int fill() throws IOException
341 // Handle the special case of a readLine that has a '\r' at the end of
342 // the buffer. In this case, we'll need to skip a '\n' if it is the
343 // next char to be read. This special case is indicated by 'pos > limit'.
344 boolean retAtEndOfBuffer = false;
347 retAtEndOfBuffer = true;
351 if (markPos >= 0 && limit == buffer.length)
355 int count = in.read(buffer, limit, buffer.length - limit);
359 if (retAtEndOfBuffer && buffer[pos] == '\n')
362 // If the mark was set to the location of the \n, then we
363 // must change it to fully pretend that the \n does not
373 public int read() throws IOException
378 if (pos >= limit && fill () <= 0)
380 return buffer[pos++];
384 /* Return the end of the line starting at this.pos and ending at limit.
385 * The index returns is *before* any line terminators, or limit
386 * if no line terminators were found.
388 private int lineEnd(int limit)
391 for (; i < limit; i++)
394 if (ch == '\n' || ch == '\r')
401 * This method reads a single line of text from the input stream, returning
402 * it as a <code>String</code>. A line is terminated by "\n", a "\r", or
403 * an "\r\n" sequence. The system dependent line separator is not used.
404 * The line termination characters are not returned in the resulting
405 * <code>String</code>.
407 * @return The line of text read, or <code>null</code> if end of stream.
409 * @exception IOException If an error occurs
411 public String readLine() throws IOException
414 // Handle the special case where a previous readLine (with no intervening
415 // reads/skips) had a '\r' at the end of the buffer.
416 // In this case, we'll need to skip a '\n' if it's the next char to be read.
417 // This special case is indicated by 'pos > limit'.
426 int i = lineEnd(limit);
429 String str = new String(buffer, pos, i - pos);
431 // If the last char in the buffer is a '\r', we must remember
432 // to check if the next char to be read after the buffer is refilled
433 // is a '\n'. If so, skip it. To indicate this condition, we set pos
434 // to be limit + 1, which normally is never possible.
435 if (buffer[i] == '\r')
436 if (pos == limit || buffer[pos] == '\n')
440 StringBuffer sbuf = new StringBuffer(200);
441 sbuf.append(buffer, pos, i - pos);
443 // We only want to return null when no characters were read before
444 // EOF. So we must keep track of this separately. Otherwise we
445 // would treat an empty `sbuf' as an EOF condition, which is wrong
446 // when there is just a newline.
456 if (ch == '\n' || ch == '\r')
458 // Check here if a '\r' was the last char in the buffer; if so,
459 // mark it as in the comment above to indicate future reads
460 // should skip a newline that is the next char read after
461 // refilling the buffer.
463 if (pos == limit || buffer[pos] == '\n')
468 sbuf.append(buffer, pos - 1, i - (pos - 1));
471 return (sbuf.length() == 0 && eof) ? null : sbuf.toString();
475 * This method skips the specified number of chars in the stream. It
476 * returns the actual number of chars skipped, which may be less than the
479 * This method first discards chars in the buffer, then calls the
480 * <code>skip</code> method on the underlying stream to skip the
483 * @param numChars The requested number of chars to skip
485 * @return The actual number of chars skipped.
487 * @exception IOException If an error occurs
489 public long skip(long count) throws IOException
496 // Yet again, we need to handle the special case of a readLine
497 // that has a '\r' at the end of the buffer. In this case, we need
498 // to ignore a '\n' if it is the next char to be read.
499 // This special case is indicated by 'pos > limit' (i.e. avail < 0).
500 // To simplify things, if we're dealing with the special case for
501 // readLine, just read the next char (since the fill method will
502 // skip the '\n' for us). By doing this, we'll have to back up pos.
503 // That's easier than trying to keep track of whether we've skipped
504 // one element or not.
507 if ((ch = read()) < 0)
512 int avail = limit - pos;
521 long todo = count - avail;
522 if (todo > buffer.length)
525 todo -= in.skip(todo);
544 private void checkStatus() throws IOException
547 throw new IOException("Stream closed");