code: public long copy(InputStream in, OutputStream out, long max) throws IOException {
          int chunk;
          long all;
          long remaining;
          
          remaining = max;
          all = 0;
          while (remaining > 0) {
              // cast is save because the buffer.length is an integer
              chunk = in.read(buffer, 0, (int) Math.min(remaining, buffer.length));
              if (chunk < 0) {
                  break;
              }
              out.write(buffer, 0, chunk);
              all += chunk;
              remaining -= chunk;
          }
          out.flush();
          return all;
      }
docs: Copies up to max bytes.
  
  @return number of bytes actually copied