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