KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > io > BufferedInputStream


1 /*
2  * @(#)BufferedInputStream.java 1.50 04/05/03
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.io;
9 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater JavaDoc;
10
11 /**
12  * A <code>BufferedInputStream</code> adds
13  * functionality to another input stream-namely,
14  * the ability to buffer the input and to
15  * support the <code>mark</code> and <code>reset</code>
16  * methods. When the <code>BufferedInputStream</code>
17  * is created, an internal buffer array is
18  * created. As bytes from the stream are read
19  * or skipped, the internal buffer is refilled
20  * as necessary from the contained input stream,
21  * many bytes at a time. The <code>mark</code>
22  * operation remembers a point in the input
23  * stream and the <code>reset</code> operation
24  * causes all the bytes read since the most
25  * recent <code>mark</code> operation to be
26  * reread before new bytes are taken from
27  * the contained input stream.
28  *
29  * @author Arthur van Hoff
30  * @version 1.50, 05/03/04
31  * @since JDK1.0
32  */

33 public
34 class BufferedInputStream extends FilterInputStream JavaDoc {
35
36     private static int defaultBufferSize = 8192;
37
38     /**
39      * The internal buffer array where the data is stored. When necessary,
40      * it may be replaced by another array of
41      * a different size.
42      */

43     protected volatile byte buf[];
44
45     /**
46      * Atomic updater to provide compareAndSet for buf. This is
47      * necessary because closes can be asynchronous. We use nullness
48      * of buf[] as primary indicator that this stream is closed. (The
49      * "in" field is also nulled out on close.)
50      */

51     private static final
52         AtomicReferenceFieldUpdater JavaDoc<BufferedInputStream JavaDoc, byte[]> bufUpdater =
53         AtomicReferenceFieldUpdater.newUpdater
54         (BufferedInputStream JavaDoc.class, byte[].class, "buf");
55
56     /**
57      * The index one greater than the index of the last valid byte in
58      * the buffer.
59      * This value is always
60      * in the range <code>0</code> through <code>buf.length</code>;
61      * elements <code>buf[0]</code> through <code>buf[count-1]
62      * </code>contain buffered input data obtained
63      * from the underlying input stream.
64      */

65     protected int count;
66
67     /**
68      * The current position in the buffer. This is the index of the next
69      * character to be read from the <code>buf</code> array.
70      * <p>
71      * This value is always in the range <code>0</code>
72      * through <code>count</code>. If it is less
73      * than <code>count</code>, then <code>buf[pos]</code>
74      * is the next byte to be supplied as input;
75      * if it is equal to <code>count</code>, then
76      * the next <code>read</code> or <code>skip</code>
77      * operation will require more bytes to be
78      * read from the contained input stream.
79      *
80      * @see java.io.BufferedInputStream#buf
81      */

82     protected int pos;
83     
84     /**
85      * The value of the <code>pos</code> field at the time the last
86      * <code>mark</code> method was called.
87      * <p>
88      * This value is always
89      * in the range <code>-1</code> through <code>pos</code>.
90      * If there is no marked position in the input
91      * stream, this field is <code>-1</code>. If
92      * there is a marked position in the input
93      * stream, then <code>buf[markpos]</code>
94      * is the first byte to be supplied as input
95      * after a <code>reset</code> operation. If
96      * <code>markpos</code> is not <code>-1</code>,
97      * then all bytes from positions <code>buf[markpos]</code>
98      * through <code>buf[pos-1]</code> must remain
99      * in the buffer array (though they may be
100      * moved to another place in the buffer array,
101      * with suitable adjustments to the values
102      * of <code>count</code>, <code>pos</code>,
103      * and <code>markpos</code>); they may not
104      * be discarded unless and until the difference
105      * between <code>pos</code> and <code>markpos</code>
106      * exceeds <code>marklimit</code>.
107      *
108      * @see java.io.BufferedInputStream#mark(int)
109      * @see java.io.BufferedInputStream#pos
110      */

111     protected int markpos = -1;
112
113     /**
114      * The maximum read ahead allowed after a call to the
115      * <code>mark</code> method before subsequent calls to the
116      * <code>reset</code> method fail.
117      * Whenever the difference between <code>pos</code>
118      * and <code>markpos</code> exceeds <code>marklimit</code>,
119      * then the mark may be dropped by setting
120      * <code>markpos</code> to <code>-1</code>.
121      *
122      * @see java.io.BufferedInputStream#mark(int)
123      * @see java.io.BufferedInputStream#reset()
124      */

125     protected int marklimit;
126
127     /**
128      * Check to make sure that underlying input stream has not been
129      * nulled out due to close; if not return it;
130      */

131     private InputStream JavaDoc getInIfOpen() throws IOException JavaDoc {
132         InputStream JavaDoc input = in;
133     if (input == null)
134         throw new IOException JavaDoc("Stream closed");
135         return input;
136     }
137
138     /**
139      * Check to make sure that buffer has not been nulled out due to
140      * close; if not return it;
141      */

142     private byte[] getBufIfOpen() throws IOException JavaDoc {
143         byte[] buffer = buf;
144     if (buffer == null)
145         throw new IOException JavaDoc("Stream closed");
146         return buffer;
147     }
148
149     /**
150      * Creates a <code>BufferedInputStream</code>
151      * and saves its argument, the input stream
152      * <code>in</code>, for later use. An internal
153      * buffer array is created and stored in <code>buf</code>.
154      *
155      * @param in the underlying input stream.
156      */

157     public BufferedInputStream(InputStream JavaDoc in) {
158     this(in, defaultBufferSize);
159     }
160
161     /**
162      * Creates a <code>BufferedInputStream</code>
163      * with the specified buffer size,
164      * and saves its argument, the input stream
165      * <code>in</code>, for later use. An internal
166      * buffer array of length <code>size</code>
167      * is created and stored in <code>buf</code>.
168      *
169      * @param in the underlying input stream.
170      * @param size the buffer size.
171      * @exception IllegalArgumentException if size <= 0.
172      */

173     public BufferedInputStream(InputStream JavaDoc in, int size) {
174     super(in);
175         if (size <= 0) {
176             throw new IllegalArgumentException JavaDoc("Buffer size <= 0");
177         }
178     buf = new byte[size];
179     }
180
181     /**
182      * Fills the buffer with more data, taking into account
183      * shuffling and other tricks for dealing with marks.
184      * Assumes that it is being called by a synchronized method.
185      * This method also assumes that all data has already been read in,
186      * hence pos > count.
187      */

188     private void fill() throws IOException JavaDoc {
189         byte[] buffer = getBufIfOpen();
190     if (markpos < 0)
191         pos = 0; /* no mark: throw away the buffer */
192     else if (pos >= buffer.length) /* no room left in buffer */
193         if (markpos > 0) { /* can throw away early part of the buffer */
194         int sz = pos - markpos;
195         System.arraycopy(buffer, markpos, buffer, 0, sz);
196         pos = sz;
197         markpos = 0;
198         } else if (buffer.length >= marklimit) {
199         markpos = -1; /* buffer got too big, invalidate mark */
200         pos = 0; /* drop buffer contents */
201         } else { /* grow buffer */
202         int nsz = pos * 2;
203         if (nsz > marklimit)
204             nsz = marklimit;
205         byte nbuf[] = new byte[nsz];
206         System.arraycopy(buffer, 0, nbuf, 0, pos);
207                 if (!bufUpdater.compareAndSet(this, buffer, nbuf)) {
208                     // Can't replace buf if there was an async close.
209
// Note: This would need to be changed if fill()
210
// is ever made accessible to multiple threads.
211
// But for now, the only way CAS can fail is via close.
212
// assert buf == null;
213
throw new IOException JavaDoc("Stream closed");
214                 }
215                 buffer = nbuf;
216         }
217         count = pos;
218     int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
219         if (n > 0)
220             count = n + pos;
221     }
222
223     /**
224      * See
225      * the general contract of the <code>read</code>
226      * method of <code>InputStream</code>.
227      *
228      * @return the next byte of data, or <code>-1</code> if the end of the
229      * stream is reached.
230      * @exception IOException if an I/O error occurs.
231      * @see java.io.FilterInputStream#in
232      */

233     public synchronized int read() throws IOException JavaDoc {
234     if (pos >= count) {
235         fill();
236         if (pos >= count)
237         return -1;
238     }
239     return getBufIfOpen()[pos++] & 0xff;
240     }
241
242     /**
243      * Read characters into a portion of an array, reading from the underlying
244      * stream at most once if necessary.
245      */

246     private int read1(byte[] b, int off, int len) throws IOException JavaDoc {
247     int avail = count - pos;
248     if (avail <= 0) {
249         /* If the requested length is at least as large as the buffer, and
250            if there is no mark/reset activity, do not bother to copy the
251            bytes into the local buffer. In this way buffered streams will
252            cascade harmlessly. */

253         if (len >= getBufIfOpen().length && markpos < 0) {
254         return getInIfOpen().read(b, off, len);
255         }
256         fill();
257         avail = count - pos;
258         if (avail <= 0) return -1;
259     }
260     int cnt = (avail < len) ? avail : len;
261     System.arraycopy(getBufIfOpen(), pos, b, off, cnt);
262     pos += cnt;
263     return cnt;
264     }
265
266     /**
267      * Reads bytes from this byte-input stream into the specified byte array,
268      * starting at the given offset.
269      *
270      * <p> This method implements the general contract of the corresponding
271      * <code>{@link InputStream#read(byte[], int, int) read}</code> method of
272      * the <code>{@link InputStream}</code> class. As an additional
273      * convenience, it attempts to read as many bytes as possible by repeatedly
274      * invoking the <code>read</code> method of the underlying stream. This
275      * iterated <code>read</code> continues until one of the following
276      * conditions becomes true: <ul>
277      *
278      * <li> The specified number of bytes have been read,
279      *
280      * <li> The <code>read</code> method of the underlying stream returns
281      * <code>-1</code>, indicating end-of-file, or
282      *
283      * <li> The <code>available</code> method of the underlying stream
284      * returns zero, indicating that further input requests would block.
285      *
286      * </ul> If the first <code>read</code> on the underlying stream returns
287      * <code>-1</code> to indicate end-of-file then this method returns
288      * <code>-1</code>. Otherwise this method returns the number of bytes
289      * actually read.
290      *
291      * <p> Subclasses of this class are encouraged, but not required, to
292      * attempt to read as many bytes as possible in the same fashion.
293      *
294      * @param b destination buffer.
295      * @param off offset at which to start storing bytes.
296      * @param len maximum number of bytes to read.
297      * @return the number of bytes read, or <code>-1</code> if the end of
298      * the stream has been reached.
299      * @exception IOException if an I/O error occurs.
300      */

301     public synchronized int read(byte b[], int off, int len)
302     throws IOException JavaDoc
303     {
304         getBufIfOpen(); // Check for closed stream
305
if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
306         throw new IndexOutOfBoundsException JavaDoc();
307     } else if (len == 0) {
308             return 0;
309         }
310
311     int n = 0;
312         for (;;) {
313             int nread = read1(b, off + n, len - n);
314             if (nread <= 0)
315                 return (n == 0) ? nread : n;
316             n += nread;
317             if (n >= len)
318                 return n;
319             // if not closed but no bytes available, return
320
InputStream JavaDoc input = in;
321             if (input != null && input.available() <= 0)
322                 return n;
323         }
324     }
325
326     /**
327      * See the general contract of the <code>skip</code>
328      * method of <code>InputStream</code>.
329      *
330      * @param n the number of bytes to be skipped.
331      * @return the actual number of bytes skipped.
332      * @exception IOException if an I/O error occurs.
333      */

334     public synchronized long skip(long n) throws IOException JavaDoc {
335         getBufIfOpen(); // Check for closed stream
336
if (n <= 0) {
337         return 0;
338     }
339     long avail = count - pos;
340      
341         if (avail <= 0) {
342             // If no mark position set then don't keep in buffer
343
if (markpos <0)
344                 return getInIfOpen().skip(n);
345             
346             // Fill in buffer to save bytes for reset
347
fill();
348             avail = count - pos;
349             if (avail <= 0)
350                 return 0;
351         }
352         
353         long skipped = (avail < n) ? avail : n;
354         pos += skipped;
355         return skipped;
356     }
357
358     /**
359      * Returns the number of bytes that can be read from this input
360      * stream without blocking.
361      * <p>
362      * The <code>available</code> method of
363      * <code>BufferedInputStream</code> returns the sum of the number
364      * of bytes remaining to be read in the buffer
365      * (<code>count&nbsp;- pos</code>)
366      * and the result of calling the <code>available</code> method of the
367      * underlying input stream.
368      *
369      * @return the number of bytes that can be read from this input
370      * stream without blocking.
371      * @exception IOException if an I/O error occurs.
372      * @see java.io.FilterInputStream#in
373      */

374     public synchronized int available() throws IOException JavaDoc {
375     return getInIfOpen().available() + (count - pos);
376     }
377
378     /**
379      * See the general contract of the <code>mark</code>
380      * method of <code>InputStream</code>.
381      *
382      * @param readlimit the maximum limit of bytes that can be read before
383      * the mark position becomes invalid.
384      * @see java.io.BufferedInputStream#reset()
385      */

386     public synchronized void mark(int readlimit) {
387     marklimit = readlimit;
388     markpos = pos;
389     }
390
391     /**
392      * See the general contract of the <code>reset</code>
393      * method of <code>InputStream</code>.
394      * <p>
395      * If <code>markpos</code> is <code>-1</code>
396      * (no mark has been set or the mark has been
397      * invalidated), an <code>IOException</code>
398      * is thrown. Otherwise, <code>pos</code> is
399      * set equal to <code>markpos</code>.
400      *
401      * @exception IOException if this stream has not been marked or
402      * if the mark has been invalidated.
403      * @see java.io.BufferedInputStream#mark(int)
404      */

405     public synchronized void reset() throws IOException JavaDoc {
406         getBufIfOpen(); // Cause exception if closed
407
if (markpos < 0)
408         throw new IOException JavaDoc("Resetting to invalid mark");
409     pos = markpos;
410     }
411
412     /**
413      * Tests if this input stream supports the <code>mark</code>
414      * and <code>reset</code> methods. The <code>markSupported</code>
415      * method of <code>BufferedInputStream</code> returns
416      * <code>true</code>.
417      *
418      * @return a <code>boolean</code> indicating if this stream type supports
419      * the <code>mark</code> and <code>reset</code> methods.
420      * @see java.io.InputStream#mark(int)
421      * @see java.io.InputStream#reset()
422      */

423     public boolean markSupported() {
424     return true;
425     }
426
427     /**
428      * Closes this input stream and releases any system resources
429      * associated with the stream.
430      *
431      * @exception IOException if an I/O error occurs.
432      */

433     public void close() throws IOException JavaDoc {
434         byte[] buffer;
435         while ( (buffer = buf) != null) {
436             if (bufUpdater.compareAndSet(this, buffer, null)) {
437                 InputStream JavaDoc input = in;
438                 in = null;
439                 if (input != null)
440                     input.close();
441                 return;
442             }
443             // Else retry in case a new buf was CASed in fill()
444
}
445     }
446 }
447
Popular Tags