public static void copyBytesToStream(InputStream inputStream,OutputStream outputStream,int length) throws IOException {
  final int BUFFER_SIZE=1024;
  byte[] buffer=new byte[BUFFER_SIZE];
  int totalRead=0;
  do {
    int readReqLen=(length == -1) ? BUFFER_SIZE : Math.min(BUFFER_SIZE,length - totalRead);
    int read=inputStream.read(buffer,0,readReqLen);
    if (read == -1) {
      if (length != -1) {
        throw createFailedToReadExpected(length,totalRead);
      }
 else {
        return;
      }
    }
    totalRead+=read;
    outputStream.write(buffer,0,read);
  }
 while (totalRead != length);
}

public static void copyBytesToStream ( InputStream inputStream , OutputStream outputStream , int length ) throws IOException { final int BUFFER_SIZE = 1024 ; byte [ ] buffer = new byte [ BUFFER_SIZE ] ; int totalRead = 0 ; do { int readReqLen = ( length == - 1 ) ? BUFFER_SIZE : Math . min ( BUFFER_SIZE , length - totalRead ) ; int read = inputStream . read ( buffer , 0 , readReqLen ) ; if ( read == - 1 ) { if ( length != - 1 ) { throw createFailedToReadExpected ( length , totalRead ) ; } else { return ; } } totalRead += read ; outputStream . write ( buffer , 0 , read ) ; } while ( totalRead != length ) ; }
copies given length amount of bytes from given inputstream to given outputstream . alternatively , if length = = - 1 , copy all bytes in inputstream until eof .
