code: public static long copy(final InputStream is, final RandomAccessFile raf,
              final long offset, long length, final LongRangeListener lrl,
              final WriteListener wl) throws IOException {
          if (length < 0) {
              throw new IllegalArgumentException("Invalid byte count: " + length);
          }
          final byte buffer[] = new byte[DEFAULT_BUFFER_SIZE];
          int bytesRead = 0;
          long written = 0;
          long filePosition = offset;
          try {
              while (length > 0) {
                  if (length < DEFAULT_BUFFER_SIZE) {
                      bytesRead = is.read(buffer, 0, (int) length);
                  } else {
                      bytesRead = is.read(buffer, 0, DEFAULT_BUFFER_SIZE);
                  }
  
                  if (bytesRead == -1) {
                      break;
                  }
  
                  length -= bytesRead;
                  synchronized (raf) {
                      raf.seek(filePosition);
                      raf.write(buffer, 0, bytesRead);
                  }
                  if (wl != null) {
                      wl.onBytesRead(bytesRead);
                  }
                  if (lrl != null) {
                      lrl.onRangeComplete(new LongRange(filePosition,
                              filePosition + bytesRead - 1));
                  }
                  filePosition += bytesRead;
                  written += bytesRead;
                  // LOG.debug("IoUtils now written: {}", written);
              }
              return written;
          } catch (final IOException e) {
              LOG.debug("Got IOException during copy", e);
              throw e;
          } catch (final RuntimeException e) {
              LOG.warn("Runtime error", e);
              throw e;
          }
      }
docs: Copy method for copying data from an {@link InputStream} to a
  {@link RandomAccessFile}.
  
  @param is The input data.
  @param raf The file to write to.
  @param offset The offset within the file to start writing at.
  @param length The number of bytes to copy.
  @return The number of bytes copied.
  @throws IOException If any IO error occurs.