2 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
29 * A <code>BufferedInputStream</code> adds
30 * functionality to another input stream-namely,
31 * the ability to buffer the input and to
32 * support the <code>mark</code> and <code>reset</code>
33 * methods. When the <code>BufferedInputStream</code>
34 * is created, an internal buffer array is
35 * created. As bytes from the stream are read
36 * or skipped, the internal buffer is refilled
37 * as necessary from the contained input stream,
38 * many bytes at a time. The <code>mark</code>
39 * operation remembers a point in the input
40 * stream and the <code>reset</code> operation
41 * causes all the bytes read since the most
42 * recent <code>mark</code> operation to be
43 * reread before new bytes are taken from
44 * the contained input stream.
46 * @author Arthur van Hoff
50 class BufferedInputStream extends FilterInputStream {
52 private static int defaultBufferSize = 8192;
55 * The internal buffer array where the data is stored. When necessary,
56 * it may be replaced by another array of
59 protected volatile byte buf[];
63 * The index one greater than the index of the last valid byte in
65 * This value is always
66 * in the range <code>0</code> through <code>buf.length</code>;
67 * elements <code>buf[0]</code> through <code>buf[count-1]
68 * </code>contain buffered input data obtained
69 * from the underlying input stream.
74 * The current position in the buffer. This is the index of the next
75 * character to be read from the <code>buf</code> array.
77 * This value is always in the range <code>0</code>
78 * through <code>count</code>. If it is less
79 * than <code>count</code>, then <code>buf[pos]</code>
80 * is the next byte to be supplied as input;
81 * if it is equal to <code>count</code>, then
82 * the next <code>read</code> or <code>skip</code>
83 * operation will require more bytes to be
84 * read from the contained input stream.
86 * @see java.io.BufferedInputStream#buf
91 * The value of the <code>pos</code> field at the time the last
92 * <code>mark</code> method was called.
94 * This value is always
95 * in the range <code>-1</code> through <code>pos</code>.
96 * If there is no marked position in the input
97 * stream, this field is <code>-1</code>. If
98 * there is a marked position in the input
99 * stream, then <code>buf[markpos]</code>
100 * is the first byte to be supplied as input
101 * after a <code>reset</code> operation. If
102 * <code>markpos</code> is not <code>-1</code>,
103 * then all bytes from positions <code>buf[markpos]</code>
104 * through <code>buf[pos-1]</code> must remain
105 * in the buffer array (though they may be
106 * moved to another place in the buffer array,
107 * with suitable adjustments to the values
108 * of <code>count</code>, <code>pos</code>,
109 * and <code>markpos</code>); they may not
110 * be discarded unless and until the difference
111 * between <code>pos</code> and <code>markpos</code>
112 * exceeds <code>marklimit</code>.
114 * @see java.io.BufferedInputStream#mark(int)
115 * @see java.io.BufferedInputStream#pos
117 protected int markpos = -1;
120 * The maximum read ahead allowed after a call to the
121 * <code>mark</code> method before subsequent calls to the
122 * <code>reset</code> method fail.
123 * Whenever the difference between <code>pos</code>
124 * and <code>markpos</code> exceeds <code>marklimit</code>,
125 * then the mark may be dropped by setting
126 * <code>markpos</code> to <code>-1</code>.
128 * @see java.io.BufferedInputStream#mark(int)
129 * @see java.io.BufferedInputStream#reset()
131 protected int marklimit;
134 * Check to make sure that underlying input stream has not been
135 * nulled out due to close; if not return it;
137 private InputStream getInIfOpen() throws IOException {
138 InputStream input = in;
140 throw new IOException("Stream closed");
145 * Check to make sure that buffer has not been nulled out due to
146 * close; if not return it;
148 private byte[] getBufIfOpen() throws IOException {
151 throw new IOException("Stream closed");
156 * Creates a <code>BufferedInputStream</code>
157 * and saves its argument, the input stream
158 * <code>in</code>, for later use. An internal
159 * buffer array is created and stored in <code>buf</code>.
161 * @param in the underlying input stream.
163 public BufferedInputStream(InputStream in) {
164 this(in, defaultBufferSize);
168 * Creates a <code>BufferedInputStream</code>
169 * with the specified buffer size,
170 * and saves its argument, the input stream
171 * <code>in</code>, for later use. An internal
172 * buffer array of length <code>size</code>
173 * is created and stored in <code>buf</code>.
175 * @param in the underlying input stream.
176 * @param size the buffer size.
177 * @exception IllegalArgumentException if size <= 0.
179 public BufferedInputStream(InputStream in, int size) {
182 throw new IllegalArgumentException("Buffer size <= 0");
184 buf = new byte[size];
188 * Fills the buffer with more data, taking into account
189 * shuffling and other tricks for dealing with marks.
190 * Assumes that it is being called by a synchronized method.
191 * This method also assumes that all data has already been read in,
194 private void fill() throws IOException {
195 byte[] buffer = getBufIfOpen();
197 pos = 0; /* no mark: throw away the buffer */
198 else if (pos >= buffer.length) /* no room left in buffer */
199 if (markpos > 0) { /* can throw away early part of the buffer */
200 int sz = pos - markpos;
201 System.arraycopy(buffer, markpos, buffer, 0, sz);
204 } else if (buffer.length >= marklimit) {
205 markpos = -1; /* buffer got too big, invalidate mark */
206 pos = 0; /* drop buffer contents */
207 } else { /* grow buffer */
211 byte nbuf[] = new byte[nsz];
212 System.arraycopy(buffer, 0, nbuf, 0, pos);
216 int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
223 * the general contract of the <code>read</code>
224 * method of <code>InputStream</code>.
226 * @return the next byte of data, or <code>-1</code> if the end of the
228 * @exception IOException if this input stream has been closed by
229 * invoking its {@link #close()} method,
230 * or an I/O error occurs.
231 * @see java.io.FilterInputStream#in
233 public synchronized int read() throws IOException {
239 return getBufIfOpen()[pos++] & 0xff;
243 * Read characters into a portion of an array, reading from the underlying
244 * stream at most once if necessary.
246 private int read1(byte[] b, int off, int len) throws IOException {
247 int avail = count - pos;
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);
258 if (avail <= 0) return -1;
260 int cnt = (avail < len) ? avail : len;
261 System.arraycopy(getBufIfOpen(), pos, b, off, cnt);
267 * Reads bytes from this byte-input stream into the specified byte array,
268 * starting at the given offset.
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>
278 * <li> The specified number of bytes have been read,
280 * <li> The <code>read</code> method of the underlying stream returns
281 * <code>-1</code>, indicating end-of-file, or
283 * <li> The <code>available</code> method of the underlying stream
284 * returns zero, indicating that further input requests would block.
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
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.
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 this input stream has been closed by
300 * invoking its {@link #close()} method,
301 * or an I/O error occurs.
303 public synchronized int read(byte b[], int off, int len)
306 getBufIfOpen(); // Check for closed stream
307 if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
308 throw new IndexOutOfBoundsException();
309 } else if (len == 0) {
315 int nread = read1(b, off + n, len - n);
317 return (n == 0) ? nread : n;
321 // if not closed but no bytes available, return
322 InputStream input = in;
323 if (input != null && input.available() <= 0)
329 * See the general contract of the <code>skip</code>
330 * method of <code>InputStream</code>.
332 * @exception IOException if the stream does not support seek,
333 * or if this input stream has been closed by
334 * invoking its {@link #close()} method, or an
337 public synchronized long skip(long n) throws IOException {
338 getBufIfOpen(); // Check for closed stream
342 long avail = count - pos;
345 // If no mark position set then don't keep in buffer
347 return getInIfOpen().skip(n);
349 // Fill in buffer to save bytes for reset
356 long skipped = (avail < n) ? avail : n;
362 * Returns an estimate of the number of bytes that can be read (or
363 * skipped over) from this input stream without blocking by the next
364 * invocation of a method for this input stream. The next invocation might be
365 * the same thread or another thread. A single read or skip of this
366 * many bytes will not block, but may read or skip fewer bytes.
368 * This method returns the sum of the number of bytes remaining to be read in
369 * the buffer (<code>count - pos</code>) and the result of calling the
370 * {@link java.io.FilterInputStream#in in}.available().
372 * @return an estimate of the number of bytes that can be read (or skipped
373 * over) from this input stream without blocking.
374 * @exception IOException if this input stream has been closed by
375 * invoking its {@link #close()} method,
376 * or an I/O error occurs.
378 public synchronized int available() throws IOException {
380 int avail = getInIfOpen().available();
381 return n > (Integer.MAX_VALUE - avail)
387 * See the general contract of the <code>mark</code>
388 * method of <code>InputStream</code>.
390 * @param readlimit the maximum limit of bytes that can be read before
391 * the mark position becomes invalid.
392 * @see java.io.BufferedInputStream#reset()
394 public synchronized void mark(int readlimit) {
395 marklimit = readlimit;
400 * See the general contract of the <code>reset</code>
401 * method of <code>InputStream</code>.
403 * If <code>markpos</code> is <code>-1</code>
404 * (no mark has been set or the mark has been
405 * invalidated), an <code>IOException</code>
406 * is thrown. Otherwise, <code>pos</code> is
407 * set equal to <code>markpos</code>.
409 * @exception IOException if this stream has not been marked or,
410 * if the mark has been invalidated, or the stream
411 * has been closed by invoking its {@link #close()}
412 * method, or an I/O error occurs.
413 * @see java.io.BufferedInputStream#mark(int)
415 public synchronized void reset() throws IOException {
416 getBufIfOpen(); // Cause exception if closed
418 throw new IOException("Resetting to invalid mark");
423 * Tests if this input stream supports the <code>mark</code>
424 * and <code>reset</code> methods. The <code>markSupported</code>
425 * method of <code>BufferedInputStream</code> returns
428 * @return a <code>boolean</code> indicating if this stream type supports
429 * the <code>mark</code> and <code>reset</code> methods.
430 * @see java.io.InputStream#mark(int)
431 * @see java.io.InputStream#reset()
433 public boolean markSupported() {
438 * Closes this input stream and releases any system resources
439 * associated with the stream.
440 * Once the stream has been closed, further read(), available(), reset(),
441 * or skip() invocations will throw an IOException.
442 * Closing a previously closed stream has no effect.
444 * @exception IOException if an I/O error occurs.
446 public void close() throws IOException {
448 while ( (buffer = buf) != null) {
449 InputStream input = in;
455 // Else retry in case a new buf was CASed in fill()