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 * @exception IllegalArgumentException if size <&eq; 0
112 public BufferedReader(Reader in
, int size
)
116 throw new IllegalArgumentException("Illegal buffer size: " + size
);
118 buffer
= new char[size
];
122 * This method closes the underlying stream and frees any associated
125 * @exception IOException If an error occurs
127 public void close() throws IOException
139 * Returns <code>true</code> to indicate that this class supports mark/reset
142 * @return <code>true</code>
144 public boolean markSupported()
150 * Mark a position in the input to which the stream can be
151 * "reset" by calling the <code>reset()</code> method. The parameter
152 * <code>readLimit</code> is the number of chars that can be read from the
153 * stream after setting the mark before the mark becomes invalid. For
154 * example, if <code>mark()</code> is called with a read limit of 10, then
155 * when 11 chars of data are read from the stream before the
156 * <code>reset()</code> method is called, then the mark is invalid and the
157 * stream object instance is not required to remember the mark.
159 * Note that the number of chars that can be remembered by this method
160 * can be greater than the size of the internal read buffer. It is also
161 * not dependent on the subordinate stream supporting mark/reset
164 * @param readLimit The number of chars that can be read before the mark
167 * @exception IOException If an error occurs
168 * @exception IllegalArgumentException if readLimit is negative.
170 public void mark(int readLimit
) throws IOException
173 throw new IllegalArgumentException("Read-ahead limit is negative");
178 // In this method we need to be aware of the special case where
179 // pos + 1 == limit. This indicates that a '\r' was the last char
180 // in the buffer during a readLine. We'll want to maintain that
181 // condition after we shift things around and if a larger buffer is
182 // needed to track readLimit, we'll have to make it one element
183 // larger to ensure we don't invalidate the mark too early, if the
184 // char following the '\r' is NOT a '\n'. This is ok because, per
185 // the spec, we are not required to invalidate when passing readLimit.
187 // Note that if 'pos > limit', then doing 'limit -= pos' will cause
188 // limit to be negative. This is the only way limit will be < 0.
190 if (pos
+ readLimit
> limit
)
192 char[] old_buffer
= buffer
;
193 int extraBuffSpace
= 0;
196 if (readLimit
+ extraBuffSpace
> limit
)
197 buffer
= new char[readLimit
+ extraBuffSpace
];
201 System
.arraycopy(old_buffer
, pos
, buffer
, 0, limit
);
208 // Maintain the relationship of 'pos > limit'.
214 // Now pos + readLimit <= buffer.length. thus if we need to read
215 // beyond buffer.length, then we are allowed to invalidate markPos.
220 * Reset the stream to the point where the <code>mark()</code> method
221 * was called. Any chars that were read after the mark point was set will
222 * be re-read during subsequent reads.
224 * This method will throw an IOException if the number of chars read from
225 * the stream since the call to <code>mark()</code> exceeds the mark limit
226 * passed when establishing the mark.
228 * @exception IOException If an error occurs;
230 public void reset() throws IOException
236 throw new IOException("mark never set or invalidated");
238 // Need to handle the extremely unlikely case where a readLine was
239 // done with a '\r' as the last char in the buffer; which was then
240 // immediately followed by a mark and a reset with NO intervening
241 // read of any sort. In that case, setting pos to markPos would
242 // lose that info and a subsequent read would thus not skip a '\n'
243 // (if one exists). The value of limit in this rare case is zero.
244 // We can assume that if limit is zero for other reasons, then
245 // pos is already set to zero and doesn't need to be readjusted.
252 * This method determines whether or not a stream is ready to be read. If
253 * this method returns <code>false</code> then this stream could (but is
254 * not guaranteed to) block on the next read attempt.
256 * @return <code>true</code> if this stream is ready to be read,
257 * <code>false</code> otherwise
259 * @exception IOException If an error occurs
261 public boolean ready() throws IOException
266 return pos
< limit
|| in
.ready();
271 * This method read chars from a stream and stores them into a caller
272 * supplied buffer. It starts storing the data at index
273 * <code>offset</code> into
274 * the buffer and attempts to read <code>len</code> chars. This method can
275 * return before reading the number of chars requested. The actual number
276 * of chars read is returned as an int. A -1 is returned to indicate the
279 * This method will block until some data can be read.
281 * @param buf The array into which the chars read should be stored
282 * @param offset The offset into the array to start storing chars
283 * @param count The requested number of chars to read
285 * @return The actual number of chars read, or -1 if end of stream.
287 * @exception IOException If an error occurs.
288 * @exception IndexOutOfBoundsException If offset and count are not
289 * valid regarding buf.
291 public int read(char[] buf
, int offset
, int count
) throws IOException
293 if (offset
< 0 || offset
+ count
> buf
.length
|| count
< 0)
294 throw new IndexOutOfBoundsException();
299 // Once again, we need to handle the special case of a readLine
300 // that has a '\r' at the end of the buffer. In this case, we'll
301 // need to skip a '\n' if it is the next char to be read.
302 // This special case is indicated by 'pos > limit'.
303 boolean retAtEndOfBuffer
= false;
305 int avail
= limit
- pos
;
312 if (limit
== buffer
.length
)
313 markPos
= -1; // read too far - invalidate the mark.
316 // Set a boolean and make pos == limit to simplify things.
317 retAtEndOfBuffer
= true;
322 // Optimization: can read directly into buf.
323 if (count
>= buffer
.length
&& !retAtEndOfBuffer
)
324 return in
.read(buf
, offset
, count
);
327 avail
= in
.read(buffer
, limit
, buffer
.length
- limit
);
328 if (retAtEndOfBuffer
&& avail
> 0 && buffer
[limit
] == '\n')
342 System
.arraycopy(buffer
, pos
, buf
, offset
, count
);
348 /* Read more data into the buffer. Update pos and limit appropriately.
349 Assumes pos==limit initially. May invalidate the mark if read too much.
350 Return number of chars read (never 0), or -1 on eof. */
351 private int fill() throws IOException
354 // Handle the special case of a readLine that has a '\r' at the end of
355 // the buffer. In this case, we'll need to skip a '\n' if it is the
356 // next char to be read. This special case is indicated by 'pos > limit'.
357 boolean retAtEndOfBuffer
= false;
360 retAtEndOfBuffer
= true;
364 if (markPos
>= 0 && limit
== buffer
.length
)
368 int count
= in
.read(buffer
, limit
, buffer
.length
- limit
);
372 if (retAtEndOfBuffer
&& buffer
[pos
] == '\n')
375 // If the mark was set to the location of the \n, then we
376 // must change it to fully pretend that the \n does not
386 public int read() throws IOException
391 if (pos
>= limit
&& fill () <= 0)
393 return buffer
[pos
++];
397 /* Return the end of the line starting at this.pos and ending at limit.
398 * The index returns is *before* any line terminators, or limit
399 * if no line terminators were found.
401 private int lineEnd(int limit
)
404 for (; i
< limit
; i
++)
407 if (ch
== '\n' || ch
== '\r')
414 * This method reads a single line of text from the input stream, returning
415 * it as a <code>String</code>. A line is terminated by "\n", a "\r", or
416 * an "\r\n" sequence. The system dependent line separator is not used.
417 * The line termination characters are not returned in the resulting
418 * <code>String</code>.
420 * @return The line of text read, or <code>null</code> if end of stream.
422 * @exception IOException If an error occurs
424 public String
readLine() throws IOException
427 // Handle the special case where a previous readLine (with no intervening
428 // reads/skips) had a '\r' at the end of the buffer.
429 // In this case, we'll need to skip a '\n' if it's the next char to be read.
430 // This special case is indicated by 'pos > limit'.
439 int i
= lineEnd(limit
);
442 String str
= new String(buffer
, pos
, i
- pos
);
444 // If the last char in the buffer is a '\r', we must remember
445 // to check if the next char to be read after the buffer is refilled
446 // is a '\n'. If so, skip it. To indicate this condition, we set pos
447 // to be limit + 1, which normally is never possible.
448 if (buffer
[i
] == '\r')
449 if (pos
== limit
|| buffer
[pos
] == '\n')
453 StringBuffer sbuf
= new StringBuffer(200);
454 sbuf
.append(buffer
, pos
, i
- pos
);
456 // We only want to return null when no characters were read before
457 // EOF. So we must keep track of this separately. Otherwise we
458 // would treat an empty `sbuf' as an EOF condition, which is wrong
459 // when there is just a newline.
463 // readLine should block. So we must not return until a -1 is reached.
466 // here count == 0 isn't sufficient to give a failure.
475 int ch
= buffer
[pos
++];
476 if (ch
== '\n' || ch
== '\r')
478 // Check here if a '\r' was the last char in the buffer; if so,
479 // mark it as in the comment above to indicate future reads
480 // should skip a newline that is the next char read after
481 // refilling the buffer.
483 if (pos
== limit
|| buffer
[pos
] == '\n')
488 sbuf
.append(buffer
, pos
- 1, i
- (pos
- 1));
491 return (sbuf
.length() == 0 && eof
) ?
null : sbuf
.toString();
495 * This method skips the specified number of chars in the stream. It
496 * returns the actual number of chars skipped, which may be less than the
499 * This method first discards chars in the buffer, then calls the
500 * <code>skip</code> method on the underlying stream to skip the
503 * @param numChars The requested number of chars to skip
505 * @return The actual number of chars skipped.
507 * @exception IOException If an error occurs.
508 * @exception IllegalArgumentException If count is negative.
510 public long skip(long count
) throws IOException
516 throw new IllegalArgumentException("skip value is negative");
519 // Yet again, we need to handle the special case of a readLine
520 // that has a '\r' at the end of the buffer. In this case, we need
521 // to ignore a '\n' if it is the next char to be read.
522 // This special case is indicated by 'pos > limit' (i.e. avail < 0).
523 // To simplify things, if we're dealing with the special case for
524 // readLine, just read the next char (since the fill method will
525 // skip the '\n' for us). By doing this, we'll have to back up pos.
526 // That's easier than trying to keep track of whether we've skipped
527 // one element or not.
530 if ((ch
= read()) < 0)
535 int avail
= limit
- pos
;
544 long todo
= count
- avail
;
545 if (todo
> buffer
.length
)
548 todo
-= in
.skip(todo
);
567 private void checkStatus() throws IOException
570 throw new IOException("Stream closed");