Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2007 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.io;
 
 
Provides utility methods for working with byte arrays and I/O streams.

Author(s):
Chris Nokleberg
Since:
1.0
 
 public final class ByteStreams {
   private static final int BUF_SIZE = 0x1000; // 4K
 
   private ByteStreams() {}

  
Returns a factory that will supply instances of java.io.ByteArrayInputStream that read from the given byte array.

Parameters:
b the input buffer
Returns:
the factory
 
       byte[] b) {
     return newInputStreamSupplier(b, 0, b.length);
   }

  
Returns a factory that will supply instances of java.io.ByteArrayInputStream that read from the given byte array.

Parameters:
b the input buffer
off the offset in the buffer of the first byte to read
len the maximum number of bytes to read from the buffer
Returns:
the factory
 
       final byte[] bfinal int offfinal int len) {
     return new InputSupplier<ByteArrayInputStream>() {
       @Override
       public ByteArrayInputStream getInput() {
         return new ByteArrayInputStream(bofflen);
       }
     };
   }

  
Writes a byte array to an output stream from the given supplier.

Parameters:
from the bytes to write
to the output supplier
Throws:
java.io.IOException if an I/O error occurs
 
   public static void write(byte[] from,
       OutputSupplier<? extends OutputStreamtothrows IOException {
     Preconditions.checkNotNull(from);
     boolean threw = true;
     OutputStream out = to.getOutput();
     try {
       out.write(from);
       threw = false;
    } finally {
      Closeables.close(outthrew);
    }
  }

  
Opens input and output streams from the given suppliers, copies all bytes from the input to the output, and closes the streams.

Parameters:
from the input factory
to the output factory
Returns:
the number of bytes copied
Throws:
java.io.IOException if an I/O error occurs
  public static long copy(InputSupplier<? extends InputStreamfrom,
      OutputSupplier<? extends OutputStreamtothrows IOException {
    int successfulOps = 0;
    InputStream in = from.getInput();
    try {
      OutputStream out = to.getOutput();
      try {
        long count = copy(inout);
        successfulOps++;
        return count;
      } finally {
        Closeables.close(outsuccessfulOps < 1);
        successfulOps++;
      }
    } finally {
      Closeables.close(insuccessfulOps < 2);
    }
  }

  
Opens an input stream from the supplier, copies all bytes from the input to the output, and closes the input stream. Does not close or flush the output stream.

Parameters:
from the input factory
to the output stream to write to
Returns:
the number of bytes copied
Throws:
java.io.IOException if an I/O error occurs
  public static long copy(InputSupplier<? extends InputStreamfrom,
      OutputStream tothrows IOException {
    boolean threw = true;
    InputStream in = from.getInput();
    try {
      long count = copy(into);
      threw = false;
      return count;
    } finally {
      Closeables.close(inthrew);
    }
  }

  
Opens an output stream from the supplier, copies all bytes from the input to the output, and closes the output stream. Does not close or flush the input stream.

Parameters:
from the input stream to read from
to the output factory
Returns:
the number of bytes copied
Throws:
java.io.IOException if an I/O error occurs
Since:
10.0
  public static long copy(InputStream from,
      OutputSupplier<? extends OutputStreamtothrows IOException {
    boolean threw = true;
    OutputStream out = to.getOutput();
    try {
      long count = copy(fromout);
      threw = false;
      return count;
    } finally {
      Closeables.close(outthrew);
    }
  }

  
Copies all bytes from the input stream to the output stream. Does not close or flush either stream.

Parameters:
from the input stream to read from
to the output stream to write to
Returns:
the number of bytes copied
Throws:
java.io.IOException if an I/O error occurs
  public static long copy(InputStream fromOutputStream to)
      throws IOException {
    byte[] buf = new byte[];
    long total = 0;
    while (true) {
      int r = from.read(buf);
      if (r == -1) {
        break;
      }
      to.write(buf, 0, r);
      total += r;
    }
    return total;
  }

  
Copies all bytes from the readable channel to the writable channel. Does not close or flush either channel.

Parameters:
from the readable channel to read from
to the writable channel to write to
Returns:
the number of bytes copied
Throws:
java.io.IOException if an I/O error occurs
  public static long copy(ReadableByteChannel from,
      WritableByteChannel tothrows IOException {
    ByteBuffer buf = ByteBuffer.allocate();
    long total = 0;
    while (from.read(buf) != -1) {
      buf.flip();
      while (buf.hasRemaining()) {
        total += to.write(buf);
      }
      buf.clear();
    }
    return total;
  }

  
Reads all bytes from an input stream into a byte array. Does not close the stream.

Parameters:
in the input stream to read from
Returns:
a byte array containing all the bytes from the stream
Throws:
java.io.IOException if an I/O error occurs
  public static byte[] toByteArray(InputStream inthrows IOException {
    copy(inout);
    return out.toByteArray();
  }

  
Returns the data from a java.io.InputStream factory as a byte array.

Parameters:
supplier the factory
Throws:
java.io.IOException if an I/O error occurs
  public static byte[] toByteArray(
      InputSupplier<? extends InputStreamsupplierthrows IOException {
    boolean threw = true;
    InputStream in = supplier.getInput();
    try {
      byte[] result = toByteArray(in);
      threw = false;
      return result;
    } finally {
      Closeables.close(inthrew);
    }
  }

  
Returns a new ByteArrayDataInput instance to read from the bytes array from the beginning.
  public static ByteArrayDataInput newDataInput(byte[] bytes) {
    return new ByteArrayDataInputStream(bytes);
  }

  
Returns a new ByteArrayDataInput instance to read from the bytes array, starting at the given position.

Throws:
java.lang.IndexOutOfBoundsException if start is negative or greater than the length of the array
  public static ByteArrayDataInput newDataInput(byte[] bytesint start) {
    Preconditions.checkPositionIndex(startbytes.length);
    return new ByteArrayDataInputStream(bytesstart);
  }
  private static class ByteArrayDataInputStream implements ByteArrayDataInput {
    final DataInput input;
    ByteArrayDataInputStream(byte[] bytes) {
      this. = new DataInputStream(new ByteArrayInputStream(bytes));
    }
    ByteArrayDataInputStream(byte[] bytesint start) {
      this. = new DataInputStream(
          new ByteArrayInputStream(bytesstartbytes.length - start));
    }
    @Override public void readFully(byte b[]) {
      try {
        .readFully(b);
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public void readFully(byte b[], int offint len) {
      try {
        .readFully(bofflen);
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public int skipBytes(int n) {
      try {
        return .skipBytes(n);
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public boolean readBoolean() {
      try {
        return .readBoolean();
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public byte readByte() {
      try {
        return .readByte();
      } catch (EOFException e) {
        throw new IllegalStateException(e);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public int readUnsignedByte() {
      try {
        return .readUnsignedByte();
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public short readShort() {
      try {
        return .readShort();
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public int readUnsignedShort() {
      try {
        return .readUnsignedShort();
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public char readChar() {
      try {
        return .readChar();
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public int readInt() {
      try {
        return .readInt();
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public long readLong() {
      try {
        return .readLong();
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public float readFloat() {
      try {
        return .readFloat();
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public double readDouble() {
      try {
        return .readDouble();
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public String readLine() {
      try {
        return .readLine();
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
    @Override public String readUTF() {
      try {
        return .readUTF();
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    }
  }

  
Returns a new ByteArrayDataOutput instance with a default size.
  public static ByteArrayDataOutput newDataOutput() {
    return new ByteArrayDataOutputStream();
  }

  
Returns a new ByteArrayDataOutput instance sized to hold size bytes before resizing.

Throws:
java.lang.IllegalArgumentException if size is negative
  public static ByteArrayDataOutput newDataOutput(int size) {
    Preconditions.checkArgument(size >= 0, "Invalid size: %s"size);
    return new ByteArrayDataOutputStream(size);
  }
  @SuppressWarnings("deprecation"// for writeBytes
  private static class ByteArrayDataOutputStream
      implements ByteArrayDataOutput {
    final DataOutput output;
      this(new ByteArrayOutputStream());
    }
    ByteArrayDataOutputStream(int size) {
      this(new ByteArrayOutputStream(size));
    }
    ByteArrayDataOutputStream(ByteArrayOutputStream byteArrayOutputSteam) {
      this. = byteArrayOutputSteam;
       = new DataOutputStream(byteArrayOutputSteam);
    }
    @Override public void write(int b) {
      try {
        .write(b);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void write(byte[] b) {
      try {
        .write(b);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void write(byte[] bint offint len) {
      try {
        .write(bofflen);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void writeBoolean(boolean v) {
      try {
        .writeBoolean(v);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void writeByte(int v) {
      try {
        .writeByte(v);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void writeBytes(String s) {
      try {
        .writeBytes(s);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void writeChar(int v) {
      try {
        .writeChar(v);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void writeChars(String s) {
      try {
        .writeChars(s);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void writeDouble(double v) {
      try {
        .writeDouble(v);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void writeFloat(float v) {
      try {
        .writeFloat(v);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void writeInt(int v) {
      try {
        .writeInt(v);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void writeLong(long v) {
      try {
        .writeLong(v);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void writeShort(int v) {
      try {
        .writeShort(v);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public void writeUTF(String s) {
      try {
        .writeUTF(s);
      } catch (IOException impossible) {
        throw new AssertionError(impossible);
      }
    }
    @Override public byte[] toByteArray() {
      return .toByteArray();
    }
  }
  // TODO(chrisn): Not all streams support skipping.
  
Returns the length of a supplied input stream, in bytes.
  public static long length(InputSupplier<? extends InputStreamsupplier)
      throws IOException {
    long count = 0;
    boolean threw = true;
    InputStream in = supplier.getInput();
    try {
      while (true) {
        // We skip only Integer.MAX_VALUE due to JDK overflow bugs.
        long amt = in.skip(.);
        if (amt == 0) {
          if (in.read() == -1) {
            threw = false;
            return count;
          }
          count++;
        } else {
          count += amt;
        }
      }
    } finally {
      Closeables.close(inthrew);
    }
  }

  
Returns true if the supplied input streams contain the same bytes.

Throws:
java.io.IOException if an I/O error occurs
  public static boolean equal(InputSupplier<? extends InputStreamsupplier1,
      InputSupplier<? extends InputStreamsupplier2throws IOException {
    byte[] buf1 = new byte[];
    byte[] buf2 = new byte[];
    boolean threw = true;
    InputStream in1 = supplier1.getInput();
    try {
      InputStream in2 = supplier2.getInput();
      try {
        while (true) {
          int read1 = read(in1buf1, 0, );
          int read2 = read(in2buf2, 0, );
          if (read1 != read2 || !Arrays.equals(buf1buf2)) {
            threw = false;
            return false;
          } else if (read1 != ) {
            threw = false;
            return true;
          }
        }
      } finally {
        Closeables.close(in2threw);
      }
    } finally {
      Closeables.close(in1threw);
    }
  }

  
Attempts to read enough bytes from the stream to fill the given byte array, with the same behavior as java.io.DataInput.readFully(byte[]). Does not close the stream.

Parameters:
in the input stream to read from.
b the buffer into which the data is read.
Throws:
java.io.EOFException if this stream reaches the end before reading all the bytes.
java.io.IOException if an I/O error occurs.
  public static void readFully(InputStream inbyte[] bthrows IOException {
    readFully(inb, 0, b.length);
  }

  
Attempts to read len bytes from the stream into the given array starting at off, with the same behavior as java.io.DataInput.readFully(byte[],int,int). Does not close the stream.

Parameters:
in the input stream to read from.
b the buffer into which the data is read.
off an int specifying the offset into the data.
len an int specifying the number of bytes to read.
Throws:
java.io.EOFException if this stream reaches the end before reading all the bytes.
java.io.IOException if an I/O error occurs.
  public static void readFully(InputStream inbyte[] bint offint len)
      throws IOException {
    if (read(inbofflen) != len) {
      throw new EOFException();
    }
  }

  
Discards n bytes of data from the input stream. This method will block until the full amount has been skipped. Does not close the stream.

Parameters:
in the input stream to read from
n the number of bytes to skip
Throws:
java.io.EOFException if this stream reaches the end before skipping all the bytes
java.io.IOException if an I/O error occurs, or the stream does not support skipping
  public static void skipFully(InputStream inlong nthrows IOException {
    while (n > 0) {
      long amt = in.skip(n);
      if (amt == 0) {
        // Force a blocking read to avoid infinite loop
        if (in.read() == -1) {
          throw new EOFException();
        }
        n--;
      } else {
        n -= amt;
      }
    }
  }

  
Process the bytes of a supplied stream

Parameters:
supplier the input stream factory
processor the object to which to pass the bytes of the stream
Returns:
the result of the byte processor
Throws:
java.io.IOException if an I/O error occurs
  public static <T> T readBytes(InputSupplier<? extends InputStreamsupplier,
      ByteProcessor<T> processorthrows IOException {
    byte[] buf = new byte[];
    boolean threw = true;
    InputStream in = supplier.getInput();
    try {
      int amt;
      do {
        amt = in.read(buf);
        if (amt == -1) {
          threw = false;
          break;
        }
      } while (processor.processBytes(buf, 0, amt));
      return processor.getResult();
    } finally {
      Closeables.close(inthrew);
    }
  }

  
Computes and returns the checksum value for a supplied input stream. The checksum object is reset when this method returns successfully.

Parameters:
supplier the input stream factory
checksum the checksum object
Returns:
the result of java.util.zip.Checksum.getValue() after updating the checksum object with all of the bytes in the stream
Throws:
java.io.IOException if an I/O error occurs
  public static long getChecksum(InputSupplier<? extends InputStreamsupplier,
      final Checksum checksumthrows IOException {
    return readBytes(suppliernew ByteProcessor<Long>() {
      @Override
      public boolean processBytes(byte[] bufint offint len) {
        checksum.update(bufofflen);
        return true;
      }
      @Override
      public Long getResult() {
        long result = checksum.getValue();
        checksum.reset();
        return result;
      }
    });
  }

  
Computes the hash code of the data supplied by supplier using hashFunction.

Parameters:
supplier the input stream factory
hashFunction the hash function to use to hash the data
Returns:
the com.google.common.hash.HashCode of all of the bytes in the input stream
Throws:
java.io.IOException if an I/O error occurs
Since:
12.0
  public static HashCode hash(
      InputSupplier<? extends InputStreamsupplierHashFunction hashFunction)
      throws IOException {
    Hasher hasher = hashFunction.newHasher();
    copy(supplier, Funnels.asOutputStream(hasher));
    return hasher.hash();
  }

  
Reads some bytes from an input stream and stores them into the buffer array b. This method blocks until len bytes of input data have been read into the array, or end of file is detected. The number of bytes read is returned, possibly zero. Does not close the stream.

A caller can detect EOF if the number of bytes read is less than len. All subsequent calls on the same stream will return zero.

If b is null, a NullPointerException is thrown. If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown. If len is zero, then no bytes are read. Otherwise, the first byte read is stored into element b[off], the next one into b[off+1], and so on. The number of bytes read is, at most, equal to len.

Parameters:
in the input stream to read from
b the buffer into which the data is read
off an int specifying the offset into the data
len an int specifying the number of bytes to read
Returns:
the number of bytes read
Throws:
java.io.IOException if an I/O error occurs
  public static int read(InputStream inbyte[] bint offint len)
      throws IOException {
    if (len < 0) {
      throw new IndexOutOfBoundsException("len is negative");
    }
    int total = 0;
    while (total < len) {
      int result = in.read(boff + totallen - total);
      if (result == -1) {
        break;
      }
      total += result;
    }
    return total;
  }

  
Returns an InputSupplier that returns input streams from the an underlying supplier, where each stream starts at the given offset and is limited to the specified number of bytes.

Parameters:
supplier the supplier from which to get the raw streams
offset the offset in bytes into the underlying stream where the returned streams will start
length the maximum length of the returned streams
Throws:
java.lang.IllegalArgumentException if offset or length are negative
  public static InputSupplier<InputStreamslice(
      final InputSupplier<? extends InputStreamsupplier,
      final long offset,
      final long length) {
    Preconditions.checkNotNull(supplier);
    Preconditions.checkArgument(offset >= 0, "offset is negative");
    Preconditions.checkArgument(length >= 0, "length is negative");
    return new InputSupplier<InputStream>() {
      @Override public InputStream getInput() throws IOException {
        InputStream in = supplier.getInput();
        if (offset > 0) {
          try {
            skipFully(inoffset);
          } catch (IOException e) {
            Closeables.closeQuietly(in);
            throw e;
          }
        }
        return new LimitInputStream(inlength);
      }
    };
  }

  
Joins multiple java.io.InputStream suppliers into a single supplier. Streams returned from the supplier will contain the concatenated data from the streams of the underlying suppliers.

Only one underlying input stream will be open at a time. Closing the joined stream will close the open underlying stream.

Reading from the joined stream will throw a java.lang.NullPointerException if any of the suppliers are null or return null.

Parameters:
suppliers the suppliers to concatenate
Returns:
a supplier that will return a stream containing the concatenated stream data
  public static InputSupplier<InputStreamjoin(final
      Iterable<? extends InputSupplier<? extends InputStream>> suppliers) {
    return new InputSupplier<InputStream>() {
      @Override public InputStream getInput() throws IOException {
        return new MultiInputStream(suppliers.iterator());
      }
    };
  }

  
Varargs form of join(java.lang.Iterable).
  public static InputSupplier<InputStreamjoin(
      InputSupplier<? extends InputStream>... suppliers) {
    return join(Arrays.asList(suppliers));
  }
New to GrepCode? Check out our FAQ X