code: public static int copyData(InputStream in, OutputStream out, int limit, int bufSize) throws IOException {
  
          if (bufSize < 1) {
              throw new IllegalArgumentException("Invalid buffer size: " + bufSize);
          }
  
          byte[] buf = new byte[bufSize];
          int total = 0;
          while (limit < 0 || total < limit) {
              int maxRead = ((limit < 0) ? buf.length : Math.min(limit - total, buf.length));
              int count = in.read(buf, 0, maxRead);
              if (count < 1) {
                  break;
              }
              out.write(buf, 0, count);
              total += count;
          }
          return total;
      }
docs: Copies up to {@code limit} bytes of data from {@code in} to {@code out}.
  <p>
  May copy less than {@code limit} bytes if {@code in} does not have that much data available.
  </p> <p>
  Allocates a temporary memory buffer of {@code bufSize} bytes for this.
  </p>
  
  @param in
  input stream to copy data from.
  @param out
  output stream to copy data to.
  @param limit
  maximum number of bytes to copy ({@code -1} to copy all bytes).
  @param bufSize
  size of the buffer to allocate (larger buffer may speed up the process).
  
  @return The number of bytes actually copied.
  
  @throws IOException
  if one is thrown by either {@code in} or {@code out}.