46 * @see java.io.OutputStream
47 * @see java.io.PushbackInputStream
48 * @since 1.0
49 */
50 public abstract class InputStream implements Closeable {
51
52 // MAX_SKIP_BUFFER_SIZE is used to determine the maximum buffer size to
53 // use when skipping.
54 private static final int MAX_SKIP_BUFFER_SIZE = 2048;
55
56 private static final int DEFAULT_BUFFER_SIZE = 8192;
57
58 /**
59 * Returns a new {@code InputStream} that reads no bytes. The returned
60 * stream is initially open. The stream is closed by calling the
61 * {@code close()} method. Subsequent calls to {@code close()} have no
62 * effect.
63 *
64 * <p> While the stream is open, the {@code available()}, {@code read()},
65 * {@code read(byte[])}, {@code read(byte[], int, int)},
66 * {@code readAllBytes()}, {@code readNBytes()}, {@code skip()}, and
67 * {@code transferTo()} methods all behave as if end of stream has been
68 * reached. After the stream has been closed, these methods all throw
69 * {@code IOException}.
70 *
71 * <p> The {@code markSupported()} method returns {@code false}. The
72 * {@code mark()} method does nothing, and the {@code reset()} method
73 * throws {@code IOException}.
74 *
75 * @return an {@code InputStream} which contains no bytes
76 *
77 * @since 11
78 */
79 public static InputStream nullInputStream() {
80 return new InputStream() {
81 private volatile boolean closed;
82
83 private void ensureOpen() throws IOException {
84 if (closed) {
85 throw new IOException("Stream closed");
86 }
106 }
107 ensureOpen();
108 return -1;
109 }
110
111 @Override
112 public byte[] readAllBytes() throws IOException {
113 ensureOpen();
114 return new byte[0];
115 }
116
117 @Override
118 public int readNBytes(byte[] b, int off, int len)
119 throws IOException {
120 Objects.checkFromIndexSize(off, len, b.length);
121 ensureOpen();
122 return 0;
123 }
124
125 @Override
126 public long skip(long n) throws IOException {
127 ensureOpen();
128 return 0L;
129 }
130
131 @Override
132 public long transferTo(OutputStream out) throws IOException {
133 Objects.requireNonNull(out);
134 ensureOpen();
135 return 0L;
136 }
137
138 @Override
139 public void close() throws IOException {
140 closed = true;
141 }
142 };
143 }
144
145 /**
216 * bytes actually read; these bytes will be stored in elements
217 * <code>b[off]</code> through <code>b[off+</code><i>k</i><code>-1]</code>,
218 * leaving elements <code>b[off+</code><i>k</i><code>]</code> through
219 * <code>b[off+len-1]</code> unaffected.
220 *
221 * <p> In every case, elements <code>b[0]</code> through
222 * <code>b[off]</code> and elements <code>b[off+len]</code> through
223 * <code>b[b.length-1]</code> are unaffected.
224 *
225 * <p> The <code>read(b,</code> <code>off,</code> <code>len)</code> method
226 * for class <code>InputStream</code> simply calls the method
227 * <code>read()</code> repeatedly. If the first such call results in an
228 * <code>IOException</code>, that exception is returned from the call to
229 * the <code>read(b,</code> <code>off,</code> <code>len)</code> method. If
230 * any subsequent call to <code>read()</code> results in a
231 * <code>IOException</code>, the exception is caught and treated as if it
232 * were end of file; the bytes read up to that point are stored into
233 * <code>b</code> and the number of bytes read before the exception
234 * occurred is returned. The default implementation of this method blocks
235 * until the requested amount of input data <code>len</code> has been read,
236 * end of file is detected, or an exception is thrown. Subclasses are encouraged
237 * to provide a more efficient implementation of this method.
238 *
239 * @param b the buffer into which the data is read.
240 * @param off the start offset in array <code>b</code>
241 * at which the data is written.
242 * @param len the maximum number of bytes to read.
243 * @return the total number of bytes read into the buffer, or
244 * <code>-1</code> if there is no more data because the end of
245 * the stream has been reached.
246 * @exception IOException If the first byte cannot be read for any reason
247 * other than end of file, or if the input stream has been closed, or if
248 * some other I/O error occurs.
249 * @exception NullPointerException If <code>b</code> is <code>null</code>.
250 * @exception IndexOutOfBoundsException If <code>off</code> is negative,
251 * <code>len</code> is negative, or <code>len</code> is greater than
252 * <code>b.length - off</code>
253 * @see java.io.InputStream#read()
254 */
255 public int read(byte b[], int off, int len) throws IOException {
256 Objects.checkFromIndexSize(off, len, b.length);
257 if (len == 0) {
270 c = read();
271 if (c == -1) {
272 break;
273 }
274 b[off + i] = (byte)c;
275 }
276 } catch (IOException ee) {
277 }
278 return i;
279 }
280
281 /**
282 * The maximum size of array to allocate.
283 * Some VMs reserve some header words in an array.
284 * Attempts to allocate larger arrays may result in
285 * OutOfMemoryError: Requested array size exceeds VM limit
286 */
287 private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
288
289 /**
290 * Reads all remaining bytes from the input stream. This method blocks until
291 * all remaining bytes have been read and end of stream is detected, or an
292 * exception is thrown. This method does not close the input stream.
293 *
294 * <p> When this stream reaches end of stream, further invocations of this
295 * method will return an empty byte array.
296 *
297 * <p> Note that this method is intended for simple cases where it is
298 * convenient to read all bytes into a byte array. It is not intended for
299 * reading input streams with large amounts of data.
300 *
301 * <p> The behavior for the case where the input stream is <i>asynchronously
302 * closed</i>, or the thread interrupted during the read, is highly input
303 * stream specific, and therefore not specified.
304 *
305 * <p> If an I/O error occurs reading from the input stream, then it may do
306 * so after some, but not all, bytes have been read. Consequently the input
307 * stream may not be at end of stream and may be in an inconsistent state.
308 * It is strongly recommended that the stream be promptly closed if an I/O
309 * error occurs.
310 *
311 * @return a byte array containing the bytes read from this input stream
312 * @throws IOException if an I/O error occurs
313 * @throws OutOfMemoryError if an array of the required size cannot be
314 * allocated. For example, if an array larger than {@code 2GB} would
315 * be required to store the bytes.
316 *
317 * @since 9
318 */
319 public byte[] readAllBytes() throws IOException {
320 List<byte[]> bufs = null;
321 byte[] result = null;
322 int total = 0;
323 int n;
324 do {
325 byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
326 int nread = 0;
327
328 // read to EOF which may read more or less than buffer size
329 while ((n = read(buf, nread, buf.length - nread)) > 0) {
330 nread += n;
331 }
332
333 if (nread > 0) {
334 if (MAX_BUFFER_SIZE - total < nread) {
335 throw new OutOfMemoryError("Required array size too large");
336 }
337 total += nread;
338 if (result == null) {
339 result = buf;
340 } else {
341 if (bufs == null) {
342 bufs = new ArrayList<>();
343 bufs.add(result);
344 }
345 bufs.add(buf);
346 }
347 }
348 } while (n >= 0); // if the last call to read returned -1, then break
349
350 if (bufs == null) {
351 if (result == null) {
352 return new byte[0];
353 }
354 return result.length == total ?
355 result : Arrays.copyOf(result, total);
356 }
357
358 result = new byte[total];
359 int offset = 0;
360 int remaining = total;
361 for (byte[] b : bufs) {
362 int len = Math.min(b.length, remaining);
363 System.arraycopy(b, 0, result, offset, len);
364 offset += len;
365 remaining -= len;
366 }
367
368 return result;
369 }
370
371 /**
372 * Reads the requested number of bytes from the input stream into the given
373 * byte array. This method blocks until {@code len} bytes of input data have
374 * been read, end of stream is detected, or an exception is thrown. The
375 * number of bytes actually read, possibly zero, is returned. This method
376 * does not close the input stream.
377 *
378 * <p> In the case where end of stream is reached before {@code len} bytes
379 * have been read, then the actual number of bytes read will be returned.
380 * When this stream reaches end of stream, further invocations of this
381 * method will return zero.
382 *
383 * <p> If {@code len} is zero, then no bytes are read and {@code 0} is
384 * returned; otherwise, there is an attempt to read up to {@code len} bytes.
385 *
386 * <p> The first byte read is stored into element {@code b[off]}, the next
387 * one in to {@code b[off+1]}, and so on. The number of bytes read is, at
388 * most, equal to {@code len}. Let <i>k</i> be the number of bytes actually
389 * read; these bytes will be stored in elements {@code b[off]} through
390 * {@code b[off+}<i>k</i>{@code -1]}, leaving elements {@code b[off+}<i>k</i>
391 * {@code ]} through {@code b[off+len-1]} unaffected.
|
46 * @see java.io.OutputStream
47 * @see java.io.PushbackInputStream
48 * @since 1.0
49 */
50 public abstract class InputStream implements Closeable {
51
52 // MAX_SKIP_BUFFER_SIZE is used to determine the maximum buffer size to
53 // use when skipping.
54 private static final int MAX_SKIP_BUFFER_SIZE = 2048;
55
56 private static final int DEFAULT_BUFFER_SIZE = 8192;
57
58 /**
59 * Returns a new {@code InputStream} that reads no bytes. The returned
60 * stream is initially open. The stream is closed by calling the
61 * {@code close()} method. Subsequent calls to {@code close()} have no
62 * effect.
63 *
64 * <p> While the stream is open, the {@code available()}, {@code read()},
65 * {@code read(byte[])}, {@code read(byte[], int, int)},
66 * {@code readAllBytes()}, {@code readNBytes(byte[], int, int)},
67 * {@code readNBytes(int)}, {@code skip()}, and
68 * {@code transferTo()} methods all behave as if end of stream has been
69 * reached. After the stream has been closed, these methods all throw
70 * {@code IOException}.
71 *
72 * <p> The {@code markSupported()} method returns {@code false}. The
73 * {@code mark()} method does nothing, and the {@code reset()} method
74 * throws {@code IOException}.
75 *
76 * @return an {@code InputStream} which contains no bytes
77 *
78 * @since 11
79 */
80 public static InputStream nullInputStream() {
81 return new InputStream() {
82 private volatile boolean closed;
83
84 private void ensureOpen() throws IOException {
85 if (closed) {
86 throw new IOException("Stream closed");
87 }
107 }
108 ensureOpen();
109 return -1;
110 }
111
112 @Override
113 public byte[] readAllBytes() throws IOException {
114 ensureOpen();
115 return new byte[0];
116 }
117
118 @Override
119 public int readNBytes(byte[] b, int off, int len)
120 throws IOException {
121 Objects.checkFromIndexSize(off, len, b.length);
122 ensureOpen();
123 return 0;
124 }
125
126 @Override
127 public byte[] readNBytes(int len)
128 throws IOException {
129 if (len < 0) {
130 throw new IndexOutOfBoundsException("len < 0");
131 }
132 ensureOpen();
133 return new byte[0];
134 }
135
136 @Override
137 public long skip(long n) throws IOException {
138 ensureOpen();
139 return 0L;
140 }
141
142 @Override
143 public long transferTo(OutputStream out) throws IOException {
144 Objects.requireNonNull(out);
145 ensureOpen();
146 return 0L;
147 }
148
149 @Override
150 public void close() throws IOException {
151 closed = true;
152 }
153 };
154 }
155
156 /**
227 * bytes actually read; these bytes will be stored in elements
228 * <code>b[off]</code> through <code>b[off+</code><i>k</i><code>-1]</code>,
229 * leaving elements <code>b[off+</code><i>k</i><code>]</code> through
230 * <code>b[off+len-1]</code> unaffected.
231 *
232 * <p> In every case, elements <code>b[0]</code> through
233 * <code>b[off]</code> and elements <code>b[off+len]</code> through
234 * <code>b[b.length-1]</code> are unaffected.
235 *
236 * <p> The <code>read(b,</code> <code>off,</code> <code>len)</code> method
237 * for class <code>InputStream</code> simply calls the method
238 * <code>read()</code> repeatedly. If the first such call results in an
239 * <code>IOException</code>, that exception is returned from the call to
240 * the <code>read(b,</code> <code>off,</code> <code>len)</code> method. If
241 * any subsequent call to <code>read()</code> results in a
242 * <code>IOException</code>, the exception is caught and treated as if it
243 * were end of file; the bytes read up to that point are stored into
244 * <code>b</code> and the number of bytes read before the exception
245 * occurred is returned. The default implementation of this method blocks
246 * until the requested amount of input data <code>len</code> has been read,
247 * end of file is detected, or an exception is thrown. Subclasses are
248 * encouraged to provide a more efficient implementation of this method.
249 *
250 * @param b the buffer into which the data is read.
251 * @param off the start offset in array <code>b</code>
252 * at which the data is written.
253 * @param len the maximum number of bytes to read.
254 * @return the total number of bytes read into the buffer, or
255 * <code>-1</code> if there is no more data because the end of
256 * the stream has been reached.
257 * @exception IOException If the first byte cannot be read for any reason
258 * other than end of file, or if the input stream has been closed, or if
259 * some other I/O error occurs.
260 * @exception NullPointerException If <code>b</code> is <code>null</code>.
261 * @exception IndexOutOfBoundsException If <code>off</code> is negative,
262 * <code>len</code> is negative, or <code>len</code> is greater than
263 * <code>b.length - off</code>
264 * @see java.io.InputStream#read()
265 */
266 public int read(byte b[], int off, int len) throws IOException {
267 Objects.checkFromIndexSize(off, len, b.length);
268 if (len == 0) {
281 c = read();
282 if (c == -1) {
283 break;
284 }
285 b[off + i] = (byte)c;
286 }
287 } catch (IOException ee) {
288 }
289 return i;
290 }
291
292 /**
293 * The maximum size of array to allocate.
294 * Some VMs reserve some header words in an array.
295 * Attempts to allocate larger arrays may result in
296 * OutOfMemoryError: Requested array size exceeds VM limit
297 */
298 private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
299
300 /**
301 * Reads a number of bytes from the input stream. The number of bytes to
302 * read is specified by the {@code len} parameter which is interpreted as
303 * an inclusive upper bound on the number to read. This method blocks
304 * until the requested number of bytes have been read, end of stream is
305 * detected, or an exception is thrown. This method does not close the
306 * input stream.
307 *
308 * <p> If {@code len} is zero, then no bytes are read and an empty byte
309 * array is returned.
310 *
311 * <p> When this stream reaches end of stream, further invocations of this
312 * method will return an empty byte array.
313 *
314 * <p> Note that this method is intended for simple cases where it is
315 * convenient to read the specified number of bytes into a byte array. It
316 * is not intended for reading large amounts of data.
317 *
318 * <p> The behavior for the case where the input stream is <i>asynchronously
319 * closed</i>, or the thread interrupted during the read, is highly input
320 * stream specific, and therefore not specified.
321 *
322 * <p> If an I/O error occurs reading from the input stream, then it may do
323 * so after some, but not all, bytes have been read. Consequently the input
324 * stream may not be at end of stream and may be in an inconsistent state.
325 * It is strongly recommended that the stream be promptly closed if an I/O
326 * error occurs.
327 *
328 * @param len the maximum number of bytes to read
329 * @return a byte array containing the bytes read from this input stream
330 * @throws IndexOutOfBoundsException if {@code len} is negative
331 * @throws IOException if an I/O error occurs
332 * @throws OutOfMemoryError if an array of the required size cannot be
333 * allocated. For example, if an array larger than {@code 2GB} would
334 * be required to store the bytes.
335 *
336 * @since 11
337 */
338 private byte[] readAtMostNBytes(int len)
339 throws IOException {
340 if (len < 0) {
341 throw new IndexOutOfBoundsException("len < 0");
342 }
343
344 List<byte[]> bufs = null;
345 byte[] result = null;
346 int total = 0;
347 int remaining = len;
348 int n;
349 do {
350 byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
351 int nread = 0;
352
353 // read to EOF which may read more or less than buffer size
354 while ((n = read(buf, nread,
355 Math.min(buf.length - nread, remaining))) > 0) {
356 nread += n;
357 remaining -= n;
358 }
359
360 if (nread > 0) {
361 if (MAX_BUFFER_SIZE - total < nread) {
362 throw new OutOfMemoryError("Required array size too large");
363 }
364 total += nread;
365 if (result == null) {
366 result = buf;
367 } else {
368 if (bufs == null) {
369 bufs = new ArrayList<>();
370 bufs.add(result);
371 }
372 bufs.add(buf);
373 }
374 }
375 // if the last call to read returned -1 or the number of bytes
376 // requested have been read then break
377 } while (n >= 0 && remaining > 0);
378
379 if (bufs == null) {
380 if (result == null) {
381 return new byte[0];
382 }
383 return result.length == total ?
384 result : Arrays.copyOf(result, total);
385 }
386
387 result = new byte[total];
388 int offset = 0;
389 remaining = total;
390 for (byte[] b : bufs) {
391 int count = Math.min(b.length, remaining);
392 System.arraycopy(b, 0, result, offset, count);
393 offset += count;
394 remaining -= count;
395 }
396
397 return result;
398 }
399
400 /**
401 * Reads all remaining bytes from the input stream. This method blocks until
402 * all remaining bytes have been read and end of stream is detected, or an
403 * exception is thrown. This method does not close the input stream.
404 *
405 * <p> When this stream reaches end of stream, further invocations of this
406 * method will return an empty byte array.
407 *
408 * <p> Note that this method is intended for simple cases where it is
409 * convenient to read all bytes into a byte array. It is not intended for
410 * reading input streams with large amounts of data.
411 *
412 * <p> The behavior for the case where the input stream is <i>asynchronously
413 * closed</i>, or the thread interrupted during the read, is highly input
414 * stream specific, and therefore not specified.
415 *
416 * <p> If an I/O error occurs reading from the input stream, then it may do
417 * so after some, but not all, bytes have been read. Consequently the input
418 * stream may not be at end of stream and may be in an inconsistent state.
419 * It is strongly recommended that the stream be promptly closed if an I/O
420 * error occurs.
421 *
422 * @return a byte array containing the bytes read from this input stream
423 * @throws IOException if an I/O error occurs
424 * @throws OutOfMemoryError if an array of the required size cannot be
425 * allocated. For example, if an array larger than {@code 2GB} would
426 * be required to store the bytes.
427 *
428 * @since 9
429 */
430 public byte[] readAllBytes() throws IOException {
431 return readAtMostNBytes(Integer.MAX_VALUE);
432 }
433
434 /**
435 * Reads up to a specified number of bytes from the input stream. This
436 * method blocks until the requested number of bytes have been read, end
437 * of stream is detected, or an exception is thrown. This method does not
438 * close the input stream.
439 *
440 * <p> If {@code len} is zero, then no bytes are read and an empty byte
441 * array is returned.
442 *
443 * <p> When this stream reaches end of stream, further invocations of this
444 * method will return an empty byte array.
445 *
446 * <p> Note that this method is intended for simple cases where it is
447 * convenient to read the specified number of bytes into a byte array. It
448 * is not intended for reading large amounts of data.
449 *
450 * <p> The behavior for the case where the input stream is <i>asynchronously
451 * closed</i>, or the thread interrupted during the read, is highly input
452 * stream specific, and therefore not specified.
453 *
454 * <p> If an I/O error occurs reading from the input stream, then it may do
455 * so after some, but not all, bytes have been read. Consequently the input
456 * stream may not be at end of stream and may be in an inconsistent state.
457 * It is strongly recommended that the stream be promptly closed if an I/O
458 * error occurs.
459 *
460 * @param len the maximum number of bytes to read
461 * @return a byte array containing the bytes read from this input stream
462 * @throws IndexOutOfBoundsException if {@code length} is negative
463 * @throws IOException if an I/O error occurs
464 * @throws OutOfMemoryError if an array of the required size cannot be
465 * allocated. For example, if an array larger than {@code 2GB} would
466 * be required to store the bytes.
467 *
468 * @since 11
469 */
470 public byte[] readNBytes(int len) throws IOException {
471 return readAtMostNBytes(len);
472 }
473
474 /**
475 * Reads the requested number of bytes from the input stream into the given
476 * byte array. This method blocks until {@code len} bytes of input data have
477 * been read, end of stream is detected, or an exception is thrown. The
478 * number of bytes actually read, possibly zero, is returned. This method
479 * does not close the input stream.
480 *
481 * <p> In the case where end of stream is reached before {@code len} bytes
482 * have been read, then the actual number of bytes read will be returned.
483 * When this stream reaches end of stream, further invocations of this
484 * method will return zero.
485 *
486 * <p> If {@code len} is zero, then no bytes are read and {@code 0} is
487 * returned; otherwise, there is an attempt to read up to {@code len} bytes.
488 *
489 * <p> The first byte read is stored into element {@code b[off]}, the next
490 * one in to {@code b[off+1]}, and so on. The number of bytes read is, at
491 * most, equal to {@code len}. Let <i>k</i> be the number of bytes actually
492 * read; these bytes will be stored in elements {@code b[off]} through
493 * {@code b[off+}<i>k</i>{@code -1]}, leaving elements {@code b[off+}<i>k</i>
494 * {@code ]} through {@code b[off+len-1]} unaffected.
|