001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.io; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkNotNull; 019import static com.google.common.base.Preconditions.checkPositionIndex; 020 021import com.google.common.annotations.Beta; 022import com.google.common.annotations.GwtIncompatible; 023import com.google.common.math.IntMath; 024import com.google.errorprone.annotations.CanIgnoreReturnValue; 025import java.io.ByteArrayInputStream; 026import java.io.ByteArrayOutputStream; 027import java.io.DataInput; 028import java.io.DataInputStream; 029import java.io.DataOutput; 030import java.io.DataOutputStream; 031import java.io.EOFException; 032import java.io.FilterInputStream; 033import java.io.IOException; 034import java.io.InputStream; 035import java.io.OutputStream; 036import java.nio.ByteBuffer; 037import java.nio.channels.FileChannel; 038import java.nio.channels.ReadableByteChannel; 039import java.nio.channels.WritableByteChannel; 040import java.util.ArrayDeque; 041import java.util.Arrays; 042import java.util.Deque; 043 044/** 045 * Provides utility methods for working with byte arrays and I/O streams. 046 * 047 * @author Chris Nokleberg 048 * @author Colin Decker 049 * @since 1.0 050 */ 051@Beta 052@GwtIncompatible 053public final class ByteStreams { 054 055 private static final int BUFFER_SIZE = 8192; 056 057 /** Creates a new byte array for buffering reads or writes. */ 058 static byte[] createBuffer() { 059 return new byte[BUFFER_SIZE]; 060 } 061 062 /** 063 * There are three methods to implement {@link FileChannel#transferTo(long, long, 064 * WritableByteChannel)}: 065 * 066 * <ol> 067 * <li>Use sendfile(2) or equivalent. Requires that both the input channel and the output 068 * channel have their own file descriptors. Generally this only happens when both channels 069 * are files or sockets. This performs zero copies - the bytes never enter userspace. 070 * <li>Use mmap(2) or equivalent. Requires that either the input channel or the output channel 071 * have file descriptors. Bytes are copied from the file into a kernel buffer, then directly 072 * into the other buffer (userspace). Note that if the file is very large, a naive 073 * implementation will effectively put the whole file in memory. On many systems with paging 074 * and virtual memory, this is not a problem - because it is mapped read-only, the kernel 075 * can always page it to disk "for free". However, on systems where killing processes 076 * happens all the time in normal conditions (i.e., android) the OS must make a tradeoff 077 * between paging memory and killing other processes - so allocating a gigantic buffer and 078 * then sequentially accessing it could result in other processes dying. This is solvable 079 * via madvise(2), but that obviously doesn't exist in java. 080 * <li>Ordinary copy. Kernel copies bytes into a kernel buffer, from a kernel buffer into a 081 * userspace buffer (byte[] or ByteBuffer), then copies them from that buffer into the 082 * destination channel. 083 * </ol> 084 * 085 * This value is intended to be large enough to make the overhead of system calls negligible, 086 * without being so large that it causes problems for systems with atypical memory management if 087 * approaches 2 or 3 are used. 088 */ 089 private static final int ZERO_COPY_CHUNK_SIZE = 512 * 1024; 090 091 private ByteStreams() {} 092 093 /** 094 * Copies all bytes from the input stream to the output stream. Does not close or flush either 095 * stream. 096 * 097 * @param from the input stream to read from 098 * @param to the output stream to write to 099 * @return the number of bytes copied 100 * @throws IOException if an I/O error occurs 101 */ 102 @CanIgnoreReturnValue 103 public static long copy(InputStream from, OutputStream to) throws IOException { 104 checkNotNull(from); 105 checkNotNull(to); 106 byte[] buf = createBuffer(); 107 long total = 0; 108 while (true) { 109 int r = from.read(buf); 110 if (r == -1) { 111 break; 112 } 113 to.write(buf, 0, r); 114 total += r; 115 } 116 return total; 117 } 118 119 /** 120 * Copies all bytes from the readable channel to the writable channel. Does not close or flush 121 * either channel. 122 * 123 * @param from the readable channel to read from 124 * @param to the writable channel to write to 125 * @return the number of bytes copied 126 * @throws IOException if an I/O error occurs 127 */ 128 @CanIgnoreReturnValue 129 public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException { 130 checkNotNull(from); 131 checkNotNull(to); 132 if (from instanceof FileChannel) { 133 FileChannel sourceChannel = (FileChannel) from; 134 long oldPosition = sourceChannel.position(); 135 long position = oldPosition; 136 long copied; 137 do { 138 copied = sourceChannel.transferTo(position, ZERO_COPY_CHUNK_SIZE, to); 139 position += copied; 140 sourceChannel.position(position); 141 } while (copied > 0 || position < sourceChannel.size()); 142 return position - oldPosition; 143 } 144 145 ByteBuffer buf = ByteBuffer.wrap(createBuffer()); 146 long total = 0; 147 while (from.read(buf) != -1) { 148 buf.flip(); 149 while (buf.hasRemaining()) { 150 total += to.write(buf); 151 } 152 buf.clear(); 153 } 154 return total; 155 } 156 157 /** Max array length on JVM. */ 158 private static final int MAX_ARRAY_LEN = Integer.MAX_VALUE - 8; 159 160 /** Large enough to never need to expand, given the geometric progression of buffer sizes. */ 161 private static final int TO_BYTE_ARRAY_DEQUE_SIZE = 20; 162 163 /** 164 * Returns a byte array containing the bytes from the buffers already in {@code bufs} (which have 165 * a total combined length of {@code totalLen} bytes) followed by all bytes remaining in the given 166 * input stream. 167 */ 168 private static byte[] toByteArrayInternal(InputStream in, Deque<byte[]> bufs, int totalLen) 169 throws IOException { 170 // Starting with an 8k buffer, double the size of each sucessive buffer. Buffers are retained 171 // in a deque so that there's no copying between buffers while reading and so all of the bytes 172 // in each new allocated buffer are available for reading from the stream. 173 for (int bufSize = BUFFER_SIZE; 174 totalLen < MAX_ARRAY_LEN; 175 bufSize = IntMath.saturatedMultiply(bufSize, 2)) { 176 byte[] buf = new byte[Math.min(bufSize, MAX_ARRAY_LEN - totalLen)]; 177 bufs.add(buf); 178 int off = 0; 179 while (off < buf.length) { 180 // always OK to fill buf; its size plus the rest of bufs is never more than MAX_ARRAY_LEN 181 int r = in.read(buf, off, buf.length - off); 182 if (r == -1) { 183 return combineBuffers(bufs, totalLen); 184 } 185 off += r; 186 totalLen += r; 187 } 188 } 189 190 // read MAX_ARRAY_LEN bytes without seeing end of stream 191 if (in.read() == -1) { 192 // oh, there's the end of the stream 193 return combineBuffers(bufs, MAX_ARRAY_LEN); 194 } else { 195 throw new OutOfMemoryError("input is too large to fit in a byte array"); 196 } 197 } 198 199 private static byte[] combineBuffers(Deque<byte[]> bufs, int totalLen) { 200 byte[] result = new byte[totalLen]; 201 int remaining = totalLen; 202 while (remaining > 0) { 203 byte[] buf = bufs.removeFirst(); 204 int bytesToCopy = Math.min(remaining, buf.length); 205 int resultOffset = totalLen - remaining; 206 System.arraycopy(buf, 0, result, resultOffset, bytesToCopy); 207 remaining -= bytesToCopy; 208 } 209 return result; 210 } 211 212 /** 213 * Reads all bytes from an input stream into a byte array. Does not close the stream. 214 * 215 * @param in the input stream to read from 216 * @return a byte array containing all the bytes from the stream 217 * @throws IOException if an I/O error occurs 218 */ 219 public static byte[] toByteArray(InputStream in) throws IOException { 220 checkNotNull(in); 221 return toByteArrayInternal(in, new ArrayDeque<byte[]>(TO_BYTE_ARRAY_DEQUE_SIZE), 0); 222 } 223 224 /** 225 * Reads all bytes from an input stream into a byte array. The given expected size is used to 226 * create an initial byte array, but if the actual number of bytes read from the stream differs, 227 * the correct result will be returned anyway. 228 */ 229 static byte[] toByteArray(InputStream in, long expectedSize) throws IOException { 230 checkArgument(expectedSize >= 0, "expectedSize (%s) must be non-negative", expectedSize); 231 if (expectedSize > MAX_ARRAY_LEN) { 232 throw new OutOfMemoryError(expectedSize + " bytes is too large to fit in a byte array"); 233 } 234 235 byte[] bytes = new byte[(int) expectedSize]; 236 int remaining = (int) expectedSize; 237 238 while (remaining > 0) { 239 int off = (int) expectedSize - remaining; 240 int read = in.read(bytes, off, remaining); 241 if (read == -1) { 242 // end of stream before reading expectedSize bytes 243 // just return the bytes read so far 244 return Arrays.copyOf(bytes, off); 245 } 246 remaining -= read; 247 } 248 249 // bytes is now full 250 int b = in.read(); 251 if (b == -1) { 252 return bytes; 253 } 254 255 // the stream was longer, so read the rest normally 256 Deque<byte[]> bufs = new ArrayDeque<byte[]>(TO_BYTE_ARRAY_DEQUE_SIZE + 2); 257 bufs.add(bytes); 258 bufs.add(new byte[] { (byte) b }); 259 return toByteArrayInternal(in, bufs, bytes.length + 1); 260 } 261 262 /** 263 * Reads and discards data from the given {@code InputStream} until the end of the stream is 264 * reached. Returns the total number of bytes read. Does not close the stream. 265 * 266 * @since 20.0 267 */ 268 @CanIgnoreReturnValue 269 public static long exhaust(InputStream in) throws IOException { 270 long total = 0; 271 long read; 272 byte[] buf = createBuffer(); 273 while ((read = in.read(buf)) != -1) { 274 total += read; 275 } 276 return total; 277 } 278 279 /** 280 * Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array from the 281 * beginning. 282 */ 283 public static ByteArrayDataInput newDataInput(byte[] bytes) { 284 return newDataInput(new ByteArrayInputStream(bytes)); 285 } 286 287 /** 288 * Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array, 289 * starting at the given position. 290 * 291 * @throws IndexOutOfBoundsException if {@code start} is negative or greater than the length of 292 * the array 293 */ 294 public static ByteArrayDataInput newDataInput(byte[] bytes, int start) { 295 checkPositionIndex(start, bytes.length); 296 return newDataInput(new ByteArrayInputStream(bytes, start, bytes.length - start)); 297 } 298 299 /** 300 * Returns a new {@link ByteArrayDataInput} instance to read from the given {@code 301 * ByteArrayInputStream}. The given input stream is not reset before being read from by the 302 * returned {@code ByteArrayDataInput}. 303 * 304 * @since 17.0 305 */ 306 public static ByteArrayDataInput newDataInput(ByteArrayInputStream byteArrayInputStream) { 307 return new ByteArrayDataInputStream(checkNotNull(byteArrayInputStream)); 308 } 309 310 private static class ByteArrayDataInputStream implements ByteArrayDataInput { 311 final DataInput input; 312 313 ByteArrayDataInputStream(ByteArrayInputStream byteArrayInputStream) { 314 this.input = new DataInputStream(byteArrayInputStream); 315 } 316 317 @Override 318 public void readFully(byte b[]) { 319 try { 320 input.readFully(b); 321 } catch (IOException e) { 322 throw new IllegalStateException(e); 323 } 324 } 325 326 @Override 327 public void readFully(byte b[], int off, int len) { 328 try { 329 input.readFully(b, off, len); 330 } catch (IOException e) { 331 throw new IllegalStateException(e); 332 } 333 } 334 335 @Override 336 public int skipBytes(int n) { 337 try { 338 return input.skipBytes(n); 339 } catch (IOException e) { 340 throw new IllegalStateException(e); 341 } 342 } 343 344 @Override 345 public boolean readBoolean() { 346 try { 347 return input.readBoolean(); 348 } catch (IOException e) { 349 throw new IllegalStateException(e); 350 } 351 } 352 353 @Override 354 public byte readByte() { 355 try { 356 return input.readByte(); 357 } catch (EOFException e) { 358 throw new IllegalStateException(e); 359 } catch (IOException impossible) { 360 throw new AssertionError(impossible); 361 } 362 } 363 364 @Override 365 public int readUnsignedByte() { 366 try { 367 return input.readUnsignedByte(); 368 } catch (IOException e) { 369 throw new IllegalStateException(e); 370 } 371 } 372 373 @Override 374 public short readShort() { 375 try { 376 return input.readShort(); 377 } catch (IOException e) { 378 throw new IllegalStateException(e); 379 } 380 } 381 382 @Override 383 public int readUnsignedShort() { 384 try { 385 return input.readUnsignedShort(); 386 } catch (IOException e) { 387 throw new IllegalStateException(e); 388 } 389 } 390 391 @Override 392 public char readChar() { 393 try { 394 return input.readChar(); 395 } catch (IOException e) { 396 throw new IllegalStateException(e); 397 } 398 } 399 400 @Override 401 public int readInt() { 402 try { 403 return input.readInt(); 404 } catch (IOException e) { 405 throw new IllegalStateException(e); 406 } 407 } 408 409 @Override 410 public long readLong() { 411 try { 412 return input.readLong(); 413 } catch (IOException e) { 414 throw new IllegalStateException(e); 415 } 416 } 417 418 @Override 419 public float readFloat() { 420 try { 421 return input.readFloat(); 422 } catch (IOException e) { 423 throw new IllegalStateException(e); 424 } 425 } 426 427 @Override 428 public double readDouble() { 429 try { 430 return input.readDouble(); 431 } catch (IOException e) { 432 throw new IllegalStateException(e); 433 } 434 } 435 436 @Override 437 public String readLine() { 438 try { 439 return input.readLine(); 440 } catch (IOException e) { 441 throw new IllegalStateException(e); 442 } 443 } 444 445 @Override 446 public String readUTF() { 447 try { 448 return input.readUTF(); 449 } catch (IOException e) { 450 throw new IllegalStateException(e); 451 } 452 } 453 } 454 455 /** Returns a new {@link ByteArrayDataOutput} instance with a default size. */ 456 public static ByteArrayDataOutput newDataOutput() { 457 return newDataOutput(new ByteArrayOutputStream()); 458 } 459 460 /** 461 * Returns a new {@link ByteArrayDataOutput} instance sized to hold {@code size} bytes before 462 * resizing. 463 * 464 * @throws IllegalArgumentException if {@code size} is negative 465 */ 466 public static ByteArrayDataOutput newDataOutput(int size) { 467 // When called at high frequency, boxing size generates too much garbage, 468 // so avoid doing that if we can. 469 if (size < 0) { 470 throw new IllegalArgumentException(String.format("Invalid size: %s", size)); 471 } 472 return newDataOutput(new ByteArrayOutputStream(size)); 473 } 474 475 /** 476 * Returns a new {@link ByteArrayDataOutput} instance which writes to the given {@code 477 * ByteArrayOutputStream}. The given output stream is not reset before being written to by the 478 * returned {@code ByteArrayDataOutput} and new data will be appended to any existing content. 479 * 480 * <p>Note that if the given output stream was not empty or is modified after the {@code 481 * ByteArrayDataOutput} is created, the contract for {@link ByteArrayDataOutput#toByteArray} will 482 * not be honored (the bytes returned in the byte array may not be exactly what was written via 483 * calls to {@code ByteArrayDataOutput}). 484 * 485 * @since 17.0 486 */ 487 public static ByteArrayDataOutput newDataOutput(ByteArrayOutputStream byteArrayOutputSteam) { 488 return new ByteArrayDataOutputStream(checkNotNull(byteArrayOutputSteam)); 489 } 490 491 @SuppressWarnings("deprecation") // for writeBytes 492 private static class ByteArrayDataOutputStream implements ByteArrayDataOutput { 493 494 final DataOutput output; 495 final ByteArrayOutputStream byteArrayOutputSteam; 496 497 ByteArrayDataOutputStream(ByteArrayOutputStream byteArrayOutputSteam) { 498 this.byteArrayOutputSteam = byteArrayOutputSteam; 499 output = new DataOutputStream(byteArrayOutputSteam); 500 } 501 502 @Override 503 public void write(int b) { 504 try { 505 output.write(b); 506 } catch (IOException impossible) { 507 throw new AssertionError(impossible); 508 } 509 } 510 511 @Override 512 public void write(byte[] b) { 513 try { 514 output.write(b); 515 } catch (IOException impossible) { 516 throw new AssertionError(impossible); 517 } 518 } 519 520 @Override 521 public void write(byte[] b, int off, int len) { 522 try { 523 output.write(b, off, len); 524 } catch (IOException impossible) { 525 throw new AssertionError(impossible); 526 } 527 } 528 529 @Override 530 public void writeBoolean(boolean v) { 531 try { 532 output.writeBoolean(v); 533 } catch (IOException impossible) { 534 throw new AssertionError(impossible); 535 } 536 } 537 538 @Override 539 public void writeByte(int v) { 540 try { 541 output.writeByte(v); 542 } catch (IOException impossible) { 543 throw new AssertionError(impossible); 544 } 545 } 546 547 @Override 548 public void writeBytes(String s) { 549 try { 550 output.writeBytes(s); 551 } catch (IOException impossible) { 552 throw new AssertionError(impossible); 553 } 554 } 555 556 @Override 557 public void writeChar(int v) { 558 try { 559 output.writeChar(v); 560 } catch (IOException impossible) { 561 throw new AssertionError(impossible); 562 } 563 } 564 565 @Override 566 public void writeChars(String s) { 567 try { 568 output.writeChars(s); 569 } catch (IOException impossible) { 570 throw new AssertionError(impossible); 571 } 572 } 573 574 @Override 575 public void writeDouble(double v) { 576 try { 577 output.writeDouble(v); 578 } catch (IOException impossible) { 579 throw new AssertionError(impossible); 580 } 581 } 582 583 @Override 584 public void writeFloat(float v) { 585 try { 586 output.writeFloat(v); 587 } catch (IOException impossible) { 588 throw new AssertionError(impossible); 589 } 590 } 591 592 @Override 593 public void writeInt(int v) { 594 try { 595 output.writeInt(v); 596 } catch (IOException impossible) { 597 throw new AssertionError(impossible); 598 } 599 } 600 601 @Override 602 public void writeLong(long v) { 603 try { 604 output.writeLong(v); 605 } catch (IOException impossible) { 606 throw new AssertionError(impossible); 607 } 608 } 609 610 @Override 611 public void writeShort(int v) { 612 try { 613 output.writeShort(v); 614 } catch (IOException impossible) { 615 throw new AssertionError(impossible); 616 } 617 } 618 619 @Override 620 public void writeUTF(String s) { 621 try { 622 output.writeUTF(s); 623 } catch (IOException impossible) { 624 throw new AssertionError(impossible); 625 } 626 } 627 628 @Override 629 public byte[] toByteArray() { 630 return byteArrayOutputSteam.toByteArray(); 631 } 632 } 633 634 private static final OutputStream NULL_OUTPUT_STREAM = 635 new OutputStream() { 636 /** Discards the specified byte. */ 637 @Override 638 public void write(int b) {} 639 640 /** Discards the specified byte array. */ 641 @Override 642 public void write(byte[] b) { 643 checkNotNull(b); 644 } 645 646 /** Discards the specified byte array. */ 647 @Override 648 public void write(byte[] b, int off, int len) { 649 checkNotNull(b); 650 } 651 652 @Override 653 public String toString() { 654 return "ByteStreams.nullOutputStream()"; 655 } 656 }; 657 658 /** 659 * Returns an {@link OutputStream} that simply discards written bytes. 660 * 661 * @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream) 662 */ 663 public static OutputStream nullOutputStream() { 664 return NULL_OUTPUT_STREAM; 665 } 666 667 /** 668 * Wraps a {@link InputStream}, limiting the number of bytes which can be read. 669 * 670 * @param in the input stream to be wrapped 671 * @param limit the maximum number of bytes to be read 672 * @return a length-limited {@link InputStream} 673 * @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream) 674 */ 675 public static InputStream limit(InputStream in, long limit) { 676 return new LimitedInputStream(in, limit); 677 } 678 679 private static final class LimitedInputStream extends FilterInputStream { 680 681 private long left; 682 private long mark = -1; 683 684 LimitedInputStream(InputStream in, long limit) { 685 super(in); 686 checkNotNull(in); 687 checkArgument(limit >= 0, "limit must be non-negative"); 688 left = limit; 689 } 690 691 @Override 692 public int available() throws IOException { 693 return (int) Math.min(in.available(), left); 694 } 695 696 // it's okay to mark even if mark isn't supported, as reset won't work 697 @Override 698 public synchronized void mark(int readLimit) { 699 in.mark(readLimit); 700 mark = left; 701 } 702 703 @Override 704 public int read() throws IOException { 705 if (left == 0) { 706 return -1; 707 } 708 709 int result = in.read(); 710 if (result != -1) { 711 --left; 712 } 713 return result; 714 } 715 716 @Override 717 public int read(byte[] b, int off, int len) throws IOException { 718 if (left == 0) { 719 return -1; 720 } 721 722 len = (int) Math.min(len, left); 723 int result = in.read(b, off, len); 724 if (result != -1) { 725 left -= result; 726 } 727 return result; 728 } 729 730 @Override 731 public synchronized void reset() throws IOException { 732 if (!in.markSupported()) { 733 throw new IOException("Mark not supported"); 734 } 735 if (mark == -1) { 736 throw new IOException("Mark not set"); 737 } 738 739 in.reset(); 740 left = mark; 741 } 742 743 @Override 744 public long skip(long n) throws IOException { 745 n = Math.min(n, left); 746 long skipped = in.skip(n); 747 left -= skipped; 748 return skipped; 749 } 750 } 751 752 /** 753 * Attempts to read enough bytes from the stream to fill the given byte array, with the same 754 * behavior as {@link DataInput#readFully(byte[])}. Does not close the stream. 755 * 756 * @param in the input stream to read from. 757 * @param b the buffer into which the data is read. 758 * @throws EOFException if this stream reaches the end before reading all the bytes. 759 * @throws IOException if an I/O error occurs. 760 */ 761 public static void readFully(InputStream in, byte[] b) throws IOException { 762 readFully(in, b, 0, b.length); 763 } 764 765 /** 766 * Attempts to read {@code len} bytes from the stream into the given array starting at {@code 767 * off}, with the same behavior as {@link DataInput#readFully(byte[], int, int)}. Does not close 768 * the stream. 769 * 770 * @param in the input stream to read from. 771 * @param b the buffer into which the data is read. 772 * @param off an int specifying the offset into the data. 773 * @param len an int specifying the number of bytes to read. 774 * @throws EOFException if this stream reaches the end before reading all the bytes. 775 * @throws IOException if an I/O error occurs. 776 */ 777 public static void readFully(InputStream in, byte[] b, int off, int len) throws IOException { 778 int read = read(in, b, off, len); 779 if (read != len) { 780 throw new EOFException( 781 "reached end of stream after reading " + read + " bytes; " + len + " bytes expected"); 782 } 783 } 784 785 /** 786 * Discards {@code n} bytes of data from the input stream. This method will block until the full 787 * amount has been skipped. Does not close the stream. 788 * 789 * @param in the input stream to read from 790 * @param n the number of bytes to skip 791 * @throws EOFException if this stream reaches the end before skipping all the bytes 792 * @throws IOException if an I/O error occurs, or the stream does not support skipping 793 */ 794 public static void skipFully(InputStream in, long n) throws IOException { 795 long skipped = skipUpTo(in, n); 796 if (skipped < n) { 797 throw new EOFException( 798 "reached end of stream after skipping " + skipped + " bytes; " + n + " bytes expected"); 799 } 800 } 801 802 /** 803 * Discards up to {@code n} bytes of data from the input stream. This method will block until 804 * either the full amount has been skipped or until the end of the stream is reached, whichever 805 * happens first. Returns the total number of bytes skipped. 806 */ 807 static long skipUpTo(InputStream in, final long n) throws IOException { 808 long totalSkipped = 0; 809 byte[] buf = createBuffer(); 810 811 while (totalSkipped < n) { 812 long remaining = n - totalSkipped; 813 long skipped = skipSafely(in, remaining); 814 815 if (skipped == 0) { 816 // Do a buffered read since skipSafely could return 0 repeatedly, for example if 817 // in.available() always returns 0 (the default). 818 int skip = (int) Math.min(remaining, buf.length); 819 if ((skipped = in.read(buf, 0, skip)) == -1) { 820 // Reached EOF 821 break; 822 } 823 } 824 825 totalSkipped += skipped; 826 } 827 828 return totalSkipped; 829 } 830 831 /** 832 * Attempts to skip up to {@code n} bytes from the given input stream, but not more than {@code 833 * in.available()} bytes. This prevents {@code FileInputStream} from skipping more bytes than 834 * actually remain in the file, something that it {@linkplain java.io.FileInputStream#skip(long) 835 * specifies} it can do in its Javadoc despite the fact that it is violating the contract of 836 * {@code InputStream.skip()}. 837 */ 838 private static long skipSafely(InputStream in, long n) throws IOException { 839 int available = in.available(); 840 return available == 0 ? 0 : in.skip(Math.min(available, n)); 841 } 842 843 /** 844 * Process the bytes of the given input stream using the given processor. 845 * 846 * @param input the input stream to process 847 * @param processor the object to which to pass the bytes of the stream 848 * @return the result of the byte processor 849 * @throws IOException if an I/O error occurs 850 * @since 14.0 851 */ 852 @CanIgnoreReturnValue // some processors won't return a useful result 853 public static <T> T readBytes(InputStream input, ByteProcessor<T> processor) throws IOException { 854 checkNotNull(input); 855 checkNotNull(processor); 856 857 byte[] buf = createBuffer(); 858 int read; 859 do { 860 read = input.read(buf); 861 } while (read != -1 && processor.processBytes(buf, 0, read)); 862 return processor.getResult(); 863 } 864 865 /** 866 * Reads some bytes from an input stream and stores them into the buffer array {@code b}. This 867 * method blocks until {@code len} bytes of input data have been read into the array, or end of 868 * file is detected. The number of bytes read is returned, possibly zero. Does not close the 869 * stream. 870 * 871 * <p>A caller can detect EOF if the number of bytes read is less than {@code len}. All subsequent 872 * calls on the same stream will return zero. 873 * 874 * <p>If {@code b} is null, a {@code NullPointerException} is thrown. If {@code off} is negative, 875 * or {@code len} is negative, or {@code off+len} is greater than the length of the array {@code 876 * b}, then an {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then no bytes 877 * are read. Otherwise, the first byte read is stored into element {@code b[off]}, the next one 878 * into {@code b[off+1]}, and so on. The number of bytes read is, at most, equal to {@code len}. 879 * 880 * @param in the input stream to read from 881 * @param b the buffer into which the data is read 882 * @param off an int specifying the offset into the data 883 * @param len an int specifying the number of bytes to read 884 * @return the number of bytes read 885 * @throws IOException if an I/O error occurs 886 */ 887 @CanIgnoreReturnValue 888 // Sometimes you don't care how many bytes you actually read, I guess. 889 // (You know that it's either going to read len bytes or stop at EOF.) 890 public static int read(InputStream in, byte[] b, int off, int len) throws IOException { 891 checkNotNull(in); 892 checkNotNull(b); 893 if (len < 0) { 894 throw new IndexOutOfBoundsException("len is negative"); 895 } 896 int total = 0; 897 while (total < len) { 898 int result = in.read(b, off + total, len - total); 899 if (result == -1) { 900 break; 901 } 902 total += result; 903 } 904 return total; 905 } 906}