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;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkPositionIndex;
 
 
Provides utility methods for working with byte arrays and I/O streams.

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

  
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 {
     checkNotNull(from);
     checkNotNull(to);
     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 {
     checkNotNull(from);
     checkNotNull(to);
     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();
  }

  
Reads all bytes from an input stream into a byte array. The given expected size is used to create an initial byte array, but if the actual number of bytes read from the stream differs, the correct result will be returned anyway.
  static byte[] toByteArray(
      InputStream inint expectedSizethrows IOException {
    byte[] bytes = new byte[expectedSize];
    int remaining = expectedSize;
    while (remaining > 0) {
      int off = expectedSize - remaining;
      int read = in.read(bytesoffremaining);
      if (read == -1) {
        // end of stream before reading expectedSize bytes
        // just return the bytes read so far
        return Arrays.copyOf(bytesoff);
      }
      remaining -= read;
    }
    // bytes is now full
    int b = in.read();
    if (b == -1) {
      return bytes;
    }
    // the stream was longer, so read the rest normally
    out.write(b); // write the byte we read when testing for end of stream
    copy(inout);
    byte[] result = new byte[bytes.length + out.size()];
    System.arraycopy(bytes, 0, result, 0, bytes.length);
    out.writeTo(resultbytes.length);
    return result;
  }

  
BAOS that provides limited access to its internal byte array.
  private static final class FastByteArrayOutputStream
      extends ByteArrayOutputStream {
    
Writes the contents of the internal buffer to the given array starting at the given offset. Assumes the array has space to hold count bytes.
    void writeTo(byte[] bint off) {
      System.arraycopy(, 0, boff);
    }
  }

  
Returns a new ByteArrayDataInput instance to read from the bytes array from the beginning.
  public static ByteArrayDataInput newDataInput(byte[] bytes) {
    return newDataInput(new ByteArrayInputStream(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) {
    checkPositionIndex(startbytes.length);
    return newDataInput(
        new ByteArrayInputStream(bytesstartbytes.length - start));
  }

  
Returns a new ByteArrayDataInput instance to read from the given ByteArrayInputStream. The given input stream is not reset before being read from by the returned ByteArrayDataInput.

Since:
17.0
  public static ByteArrayDataInput newDataInput(
      ByteArrayInputStream byteArrayInputStream) {
    return new ByteArrayDataInputStream(checkNotNull(byteArrayInputStream));
  }
  private static class ByteArrayDataInputStream implements ByteArrayDataInput {
    final DataInput input;
    ByteArrayDataInputStream(ByteArrayInputStream byteArrayInputStream) {
      this. = new DataInputStream(byteArrayInputStream);
    }
    @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 newDataOutput(new ByteArrayOutputStream());
  }

  
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) {
    checkArgument(size >= 0, "Invalid size: %s"size);
    return newDataOutput(new ByteArrayOutputStream(size));
  }

  
Returns a new ByteArrayDataOutput instance which writes to the given ByteArrayOutputStream. The given output stream is not reset before being written to by the returned ByteArrayDataOutput and new data will be appended to any existing content.

Note that if the given output stream was not empty or is modified after the ByteArrayDataOutput is created, the contract for ByteArrayDataOutput.toByteArray() will not be honored (the bytes returned in the byte array may not be exactly what was written via calls to ByteArrayDataOutput).

Since:
17.0
      ByteArrayOutputStream byteArrayOutputSteam) {
    return new ByteArrayDataOutputStream(checkNotNull(byteArrayOutputSteam));
  }
  @SuppressWarnings("deprecation"// for writeBytes
  private static class ByteArrayDataOutputStream
      implements ByteArrayDataOutput {
    final DataOutput output;
    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();
    }
  }
  private static final OutputStream NULL_OUTPUT_STREAM =
      new OutputStream() {
        
Discards the specified byte.
        @Override public void write(int b) {
        }
        
Discards the specified byte array.
        @Override public void write(byte[] b) {
          checkNotNull(b);
        }
        
Discards the specified byte array.
        @Override public void write(byte[] bint offint len) {
          checkNotNull(b);
        }
        @Override
        public String toString() {
          return "ByteStreams.nullOutputStream()";
        }
      };

  
Returns an java.io.OutputStream that simply discards written bytes.

Since:
14.0 (since 1.0 as com.google.common.io.NullOutputStream)
  public static OutputStream nullOutputStream() {
    return ;
  }

  
Wraps a java.io.InputStream, limiting the number of bytes which can be read.

Parameters:
in the input stream to be wrapped
limit the maximum number of bytes to be read
Returns:
a length-limited java.io.InputStream
Since:
14.0 (since 1.0 as com.google.common.io.LimitInputStream)
  public static InputStream limit(InputStream inlong limit) {
    return new LimitedInputStream(inlimit);
  }
  private static final class LimitedInputStream extends FilterInputStream {
    private long left;
    private long mark = -1;
    LimitedInputStream(InputStream inlong limit) {
      super(in);
      checkNotNull(in);
      checkArgument(limit >= 0, "limit must be non-negative");
       = limit;
    }
    @Override public int available() throws IOException {
      return (int) Math.min(.available(), );
    }
    // it's okay to mark even if mark isn't supported, as reset won't work
    @Override public synchronized void mark(int readLimit) {
      .mark(readLimit);
       = ;
    }
    @Override public int read() throws IOException {
      if ( == 0) {
        return -1;
      }
      int result = .read();
      if (result != -1) {
        --;
      }
      return result;
    }
    @Override public int read(byte[] bint offint lenthrows IOException {
      if ( == 0) {
        return -1;
      }
      len = (int) Math.min(len);
      int result = .read(bofflen);
      if (result != -1) {
         -= result;
      }
      return result;
    }
    @Override public synchronized void reset() throws IOException {
      if (!.markSupported()) {
        throw new IOException("Mark not supported");
      }
      if ( == -1) {
        throw new IOException("Mark not set");
      }
      .reset();
       = ;
    }
    @Override public long skip(long nthrows IOException {
      n = Math.min(n);
      long skipped = .skip(n);
       -= skipped;
      return skipped;
    }
  }

  
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 lenthrows IOException {
    int read = read(inbofflen);
    if (read != len) {
      throw new EOFException("reached end of stream after reading "
          + read + " bytes; " + len + " bytes expected");
    }
  }

  
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 {
    long toSkip = n;
    while (n > 0) {
      long amt = in.skip(n);
      if (amt == 0) {
        // Force a blocking read to avoid infinite loop
        if (in.read() == -1) {
          long skipped = toSkip - n;
          throw new EOFException("reached end of stream after skipping "
              + skipped + " bytes; " + toSkip + " bytes expected");
        }
        n--;
      } else {
        n -= amt;
      }
    }
  }

  
Process the bytes of the given input stream using the given processor.

Parameters:
input the input stream to process
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
Since:
14.0
  public static <T> T readBytes(
      InputStream inputByteProcessor<T> processorthrows IOException {
    checkNotNull(input);
    checkNotNull(processor);
    byte[] buf = new byte[];
    int read;
    do {
      read = input.read(buf);
    } while (read != -1 && processor.processBytes(buf, 0, read));
    return processor.getResult();
  }

  
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 {
    checkNotNull(in);
    checkNotNull(b);
    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;
  }
New to GrepCode? Check out our FAQ X