source: trunk/gcc/libjava/java/io/BufferedReader.java

Last change on this file was 1392, checked in by bird, 21 years ago

This commit was generated by cvs2svn to compensate for changes in r1391,
which included commits to RCS files with non-trunk default branches.

  • Property cvs2svn:cvs-rev set to 1.1.1.2
  • Property svn:eol-style set to native
  • Property svn:executable set to *
File size: 17.1 KB
Line 
1/* BufferedReader.java
2 Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
3
4This file is part of GNU Classpath.
5
6GNU Classpath is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
8the Free Software Foundation; either version 2, or (at your option)
9any later version.
10
11GNU Classpath is distributed in the hope that it will be useful, but
12WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GNU Classpath; see the file COPYING. If not, write to the
18Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
1902111-1307 USA.
20
21Linking this library statically or dynamically with other modules is
22making a combined work based on this library. Thus, the terms and
23conditions of the GNU General Public License cover the whole
24combination.
25
26As a special exception, the copyright holders of this library give you
27permission to link this library with independent modules to produce an
28executable, regardless of the license terms of these independent
29modules, and to copy and distribute the resulting executable under
30terms of your choice, provided that you also meet, for each linked
31independent module, the terms and conditions of the license of that
32module. An independent module is a module which is not derived from
33or based on this library. If you modify this library, you may extend
34this exception to your version of the library, but you are not
35obligated to do so. If you do not wish to do so, delete this
36exception statement from your version. */
37
38
39package java.io;
40
41/* Written using "Java Class Libraries", 2nd edition, plus online
42 * API docs for JDK 1.2 beta from http://www.javasoft.com.
43 * Status: Believed complete and correct.
44 */
45
46/**
47 * This subclass of <code>FilterReader</code> buffers input from an
48 * underlying implementation to provide a possibly more efficient read
49 * mechanism. It maintains the buffer and buffer state in instance
50 * variables that are available to subclasses. The default buffer size
51 * of 512 chars can be overridden by the creator of the stream.
52 * <p>
53 * This class also implements mark/reset functionality. It is capable
54 * of remembering any number of input chars, to the limits of
55 * system memory or the size of <code>Integer.MAX_VALUE</code>
56 *
57 * @author Per Bothner <bothner@cygnus.com>
58 * @author Aaron M. Renn <arenn@urbanophile.com>
59 */
60public class BufferedReader extends Reader
61{
62 Reader in;
63 char[] buffer;
64 /* Index of current read position. Must be >= 0 and <= limit. */
65 /* There is a special case where pos may be equal to limit+1; this
66 * is used as an indicator that a readLine was done with a '\r' was
67 * the very last char in the buffer. Since we don't want to read-ahead
68 * and potentially block, we set pos this way to indicate the situation
69 * and deal with it later. Doing it this way rather than having a
70 * separate boolean field to indicate the condition has the advantage
71 * that it is self-clearing on things like mark/reset.
72 */
73 int pos;
74 /* Limit of valid data in buffer. Must be >= pos and <= buffer.length. */
75 /* This can be < pos in the one special case described above. */
76 int limit;
77
78 /* The value -1 means there is no mark, or the mark has been invalidated.
79 Otherwise, markPos is the index in the buffer of the marked position.
80 Must be >= 0 and <= pos.
81 Note we do not explicitly store the read-limit.
82 The implicit read-limit is (buffer.length - markPos), which is
83 guaranteed to be >= the read-limit requested in the call to mark. */
84 int markPos = -1;
85
86 // The JCL book specifies the default buffer size as 8K characters.
87 // This is package-private because it is used by LineNumberReader.
88 static final int DEFAULT_BUFFER_SIZE = 8192;
89
90 /**
91 * Create a new <code>BufferedReader</code> that will read from the
92 * specified subordinate stream with a default buffer size of 4096 chars.
93 *
94 * @param in The subordinate stream to read from
95 */
96 public BufferedReader(Reader in)
97 {
98 this(in, DEFAULT_BUFFER_SIZE);
99 }
100
101 /**
102 * Create a new <code>BufferedReader</code> that will read from the
103 * specified subordinate stream with a buffer size that is specified by the
104 * caller.
105 *
106 * @param in The subordinate stream to read from
107 * @param bufsize The buffer size to use
108 */
109 public BufferedReader(Reader in, int size)
110 {
111 super(in.lock);
112 this.in = in;
113 buffer = new char[size];
114 }
115
116 /**
117 * This method closes the stream
118 *
119 * @exception IOException If an error occurs
120 */
121 public void close() throws IOException
122 {
123 synchronized (lock)
124 {
125 if (in != null)
126 in.close();
127 in = null;
128 buffer = null;
129 }
130 }
131
132 /**
133 * Returns <code>true</code> to indicate that this class supports mark/reset
134 * functionality.
135 *
136 * @return <code>true</code>
137 */
138 public boolean markSupported()
139 {
140 return true;
141 }
142
143 /**
144 * Mark a position in the input to which the stream can be
145 * "reset" by calling the <code>reset()</code> method. The parameter
146 * <code>readlimit</code> is the number of chars that can be read from the
147 * stream after setting the mark before the mark becomes invalid. For
148 * example, if <code>mark()</code> is called with a read limit of 10, then
149 * when 11 chars of data are read from the stream before the
150 * <code>reset()</code> method is called, then the mark is invalid and the
151 * stream object instance is not required to remember the mark.
152 * <p>
153 * Note that the number of chars that can be remembered by this method
154 * can be greater than the size of the internal read buffer. It is also
155 * not dependent on the subordinate stream supporting mark/reset
156 * functionality.
157 *
158 * @param readlimit The number of chars that can be read before the mark
159 * becomes invalid
160 *
161 * @exception IOException If an error occurs
162 */
163 public void mark(int readLimit) throws IOException
164 {
165 synchronized (lock)
166 {
167 checkStatus();
168 // In this method we need to be aware of the special case where
169 // pos + 1 == limit. This indicates that a '\r' was the last char
170 // in the buffer during a readLine. We'll want to maintain that
171 // condition after we shift things around and if a larger buffer is
172 // needed to track readLimit, we'll have to make it one element
173 // larger to ensure we don't invalidate the mark too early, if the
174 // char following the '\r' is NOT a '\n'. This is ok because, per
175 // the spec, we are not required to invalidate when passing readLimit.
176 //
177 // Note that if 'pos > limit', then doing 'limit -= pos' will cause
178 // limit to be negative. This is the only way limit will be < 0.
179
180 if (pos + readLimit > limit)
181 {
182 char[] old_buffer = buffer;
183 int extraBuffSpace = 0;
184 if (pos > limit)
185 extraBuffSpace = 1;
186 if (readLimit + extraBuffSpace > limit)
187 buffer = new char[readLimit + extraBuffSpace];
188 limit -= pos;
189 if (limit >= 0)
190 {
191 System.arraycopy(old_buffer, pos, buffer, 0, limit);
192 pos = 0;
193 }
194 }
195
196 if (limit < 0)
197 {
198 // Maintain the relationship of 'pos > limit'.
199 pos = 1;
200 limit = markPos = 0;
201 }
202 else
203 markPos = pos;
204 // Now pos + readLimit <= buffer.length. thus if we need to read
205 // beyond buffer.length, then we are allowed to invalidate markPos.
206 }
207 }
208
209 /**
210 * Reset the stream to the point where the <code>mark()</code> method
211 * was called. Any chars that were read after the mark point was set will
212 * be re-read during subsequent reads.
213 * <p>
214 * This method will throw an IOException if the number of chars read from
215 * the stream since the call to <code>mark()</code> exceeds the mark limit
216 * passed when establishing the mark.
217 *
218 * @exception IOException If an error occurs;
219 */
220 public void reset() throws IOException
221 {
222 synchronized (lock)
223 {
224 checkStatus();
225 if (markPos < 0)
226 throw new IOException("mark never set or invalidated");
227
228 // Need to handle the extremely unlikely case where a readLine was
229 // done with a '\r' as the last char in the buffer; which was then
230 // immediately followed by a mark and a reset with NO intervening
231 // read of any sort. In that case, setting pos to markPos would
232 // lose that info and a subsequent read would thus not skip a '\n'
233 // (if one exists). The value of limit in this rare case is zero.
234 // We can assume that if limit is zero for other reasons, then
235 // pos is already set to zero and doesn't need to be readjusted.
236 if (limit > 0)
237 pos = markPos;
238 }
239 }
240
241 /**
242 * This method determines whether or not a stream is ready to be read. If
243 * This method returns <code>false</code> then this stream could (but is
244 * not guaranteed to) block on the next read attempt.
245 *
246 * @return <code>true</code> if this stream is ready to be read, <code>false</code> otherwise
247 *
248 * @exception IOException If an error occurs
249 */
250 public boolean ready() throws IOException
251 {
252 synchronized (lock)
253 {
254 checkStatus();
255 return pos < limit || in.ready();
256 }
257 }
258
259 /**
260 * This method read chars from a stream and stores them into a caller
261 * supplied buffer. It starts storing the data at index <code>offset</code> into
262 * the buffer and attempts to read <code>len</code> chars. This method can
263 * return before reading the number of chars requested. The actual number
264 * of chars read is returned as an int. A -1 is returned to indicate the
265 * end of the stream.
266 * <p>
267 * This method will block until some data can be read.
268 *
269 * @param buf The array into which the chars read should be stored
270 * @param offset The offset into the array to start storing chars
271 * @param count The requested number of chars to read
272 *
273 * @return The actual number of chars read, or -1 if end of stream.
274 *
275 * @exception IOException If an error occurs.
276 */
277 public int read(char[] buf, int offset, int count) throws IOException
278 {
279 synchronized (lock)
280 {
281 checkStatus();
282 // Once again, we need to handle the special case of a readLine
283 // that has a '\r' at the end of the buffer. In this case, we'll
284 // need to skip a '\n' if it is the next char to be read.
285 // This special case is indicated by 'pos > limit'.
286 boolean retAtEndOfBuffer = false;
287
288 int avail = limit - pos;
289 if (count > avail)
290 {
291 if (avail > 0)
292 count = avail;
293 else // pos >= limit
294 {
295 if (limit == buffer.length)
296 markPos = -1; // read too far - invalidate the mark.
297 if (pos > limit)
298 {
299 // Set a boolean and make pos == limit to simplify things.
300 retAtEndOfBuffer = true;
301 --pos;
302 }
303 if (markPos < 0)
304 {
305 // Optimization: can read directly into buf.
306 if (count >= buffer.length && !retAtEndOfBuffer)
307 return in.read(buf, offset, count);
308 pos = limit = 0;
309 }
310 avail = in.read(buffer, limit, buffer.length - limit);
311 if (retAtEndOfBuffer && avail > 0 && buffer[limit] == '\n')
312 {
313 --avail;
314 limit++;
315 }
316 if (avail < count)
317 {
318 if (avail <= 0)
319 return avail;
320 count = avail;
321 }
322 limit += avail;
323 }
324 }
325 System.arraycopy(buffer, pos, buf, offset, count);
326 pos += count;
327 return count;
328 }
329 }
330
331 /* Read more data into the buffer. Update pos and limit appropriately.
332 Assumes pos==limit initially. May invalidate the mark if read too much.
333 Return number of chars read (never 0), or -1 on eof. */
334 private int fill() throws IOException
335 {
336 checkStatus();
337 // Handle the special case of a readLine that has a '\r' at the end of
338 // the buffer. In this case, we'll need to skip a '\n' if it is the
339 // next char to be read. This special case is indicated by 'pos > limit'.
340 boolean retAtEndOfBuffer = false;
341 if (pos > limit)
342 {
343 retAtEndOfBuffer = true;
344 --pos;
345 }
346
347 if (markPos >= 0 && limit == buffer.length)
348 markPos = -1;
349 if (markPos < 0)
350 pos = limit = 0;
351 int count = in.read(buffer, limit, buffer.length - limit);
352 if (count > 0)
353 limit += count;
354
355 if (retAtEndOfBuffer && buffer[pos] == '\n')
356 {
357 --count;
358 // If the mark was set to the location of the \n, then we
359 // must change it to fully pretend that the \n does not
360 // exist.
361 if (markPos == pos)
362 ++markPos;
363 ++pos;
364 }
365
366 return count;
367 }
368
369 public int read() throws IOException
370 {
371 synchronized (lock)
372 {
373 checkStatus();
374 if (pos >= limit && fill () <= 0)
375 return -1;
376 return buffer[pos++];
377 }
378 }
379
380 /* Return the end of the line starting at this.pos and ending at limit.
381 * The index returns is *before* any line terminators, or limit
382 * if no line terminators were found.
383 */
384 private int lineEnd(int limit)
385 {
386 int i = pos;
387 for (; i < limit; i++)
388 {
389 char ch = buffer[i];
390 if (ch == '\n' || ch == '\r')
391 break;
392 }
393 return i;
394 }
395
396 /**
397 * This method reads a single line of text from the input stream, returning
398 * it as a <code>String</code>. A line is terminated by "\n", a "\r", or
399 * an "\r\n" sequence. The system dependent line separator is not used.
400 * The line termination characters are not returned in the resulting
401 * <code>String</code>.
402 *
403 * @return The line of text read, or <code>null</code> if end of stream.
404 *
405 * @exception IOException If an error occurs
406 */
407 public String readLine() throws IOException
408 {
409 checkStatus();
410 // Handle the special case where a previous readLine (with no intervening
411 // reads/skips) had a '\r' at the end of the buffer.
412 // In this case, we'll need to skip a '\n' if it's the next char to be read.
413 // This special case is indicated by 'pos > limit'.
414 if (pos > limit)
415 {
416 int ch = read();
417 if (ch < 0)
418 return null;
419 if (ch != '\n')
420 --pos;
421 }
422 int i = lineEnd(limit);
423 if (i < limit)
424 {
425 String str = new String(buffer, pos, i - pos);
426 pos = i + 1;
427 // If the last char in the buffer is a '\r', we must remember
428 // to check if the next char to be read after the buffer is refilled
429 // is a '\n'. If so, skip it. To indicate this condition, we set pos
430 // to be limit + 1, which normally is never possible.
431 if (buffer[i] == '\r')
432 if (pos == limit || buffer[pos] == '\n')
433 pos++;
434 return str;
435 }
436 StringBuffer sbuf = new StringBuffer(200);
437 sbuf.append(buffer, pos, i - pos);
438 pos = i;
439 // We only want to return null when no characters were read before
440 // EOF. So we must keep track of this separately. Otherwise we
441 // would treat an empty `sbuf' as an EOF condition, which is wrong
442 // when there is just a newline.
443 boolean eof = false;
444 for (;;)
445 {
446 int ch = read();
447 if (ch < 0)
448 {
449 eof = true;
450 break;
451 }
452 if (ch == '\n' || ch == '\r')
453 {
454 // Check here if a '\r' was the last char in the buffer; if so,
455 // mark it as in the comment above to indicate future reads
456 // should skip a newline that is the next char read after
457 // refilling the buffer.
458 if (ch == '\r')
459 if (pos == limit || buffer[pos] == '\n')
460 pos++;
461 break;
462 }
463 i = lineEnd(limit);
464 sbuf.append(buffer, pos - 1, i - (pos - 1));
465 pos = i;
466 }
467 return (sbuf.length() == 0 && eof) ? null : sbuf.toString();
468 }
469
470 /**
471 * This method skips the specified number of chars in the stream. It
472 * returns the actual number of chars skipped, which may be less than the
473 * requested amount.
474 * <p>
475 * This method first discards chars in the buffer, then calls the
476 * <code>skip</code> method on the underlying stream to skip the remaining chars.
477 *
478 * @param num_chars The requested number of chars to skip
479 *
480 * @return The actual number of chars skipped.
481 *
482 * @exception IOException If an error occurs
483 */
484 public long skip(long count) throws IOException
485 {
486 synchronized (lock)
487 {
488 checkStatus();
489 if (count <= 0)
490 return 0;
491 // Yet again, we need to handle the special case of a readLine
492 // that has a '\r' at the end of the buffer. In this case, we need
493 // to ignore a '\n' if it is the next char to be read.
494 // This special case is indicated by 'pos > limit' (i.e. avail < 0).
495 // To simplify things, if we're dealing with the special case for
496 // readLine, just read the next char (since the fill method will
497 // skip the '\n' for us). By doing this, we'll have to back up pos.
498 // That's easier than trying to keep track of whether we've skipped
499 // one element or not.
500 int ch;
501 if (pos > limit)
502 if ((ch = read()) < 0)
503 return 0;
504 else
505 --pos;
506
507 int avail = limit - pos;
508
509 if (count < avail)
510 {
511 pos += count;
512 return count;
513 }
514
515 pos = limit;
516 long todo = count - avail;
517 if (todo > buffer.length)
518 {
519 markPos = -1;
520 todo -= in.skip(todo);
521 }
522 else
523 {
524 while (todo > 0)
525 {
526 avail = fill();
527 if (avail <= 0)
528 break;
529 if (avail > todo)
530 avail = (int) todo;
531 pos += avail;
532 todo -= avail;
533 }
534 }
535 return count - todo;
536 }
537 }
538
539 private void checkStatus() throws IOException
540 {
541 if (in == null)
542 throw new IOException("Stream closed");
543 }
544}
Note: See TracBrowser for help on using the repository browser.