code: public static void copy(InputStream in, OutputStream out, long byteCount) throws IOException {
          byte buffer[] = new byte[bufferSize];
          int len = bufferSize;
  
          if (byteCount >= 0) {
              while (byteCount > 0) {
                  int max = byteCount < bufferSize ? (int) byteCount : bufferSize;
                  len = in.read(buffer, 0, max);
  
                  if (len == -1)
                      break;
  
                  byteCount -= len;
                  out.write(buffer, 0, len);
              }
          } else {
              while (true) {
                  len = in.read(buffer, 0, bufferSize);
                  if (len < 0)
                      break;
                  out.write(buffer, 0, len);
              }
          }
      }
docs: Copy Stream in to Stream for byteCount bytes or until EOF or exception.
  
  @param in        the stream to read from
  @param out       the stream to write to
  @param byteCount the number of bytes to copy
  @throws IOException if unable to copy the streams