code: public static void writeBytes(ByteBuffer bytes, OutputStream out) throws IOException {
      final int BUFFER_LENGTH = 1024;
      byte[] buffer;
  
      if (bytes.remaining() >= BUFFER_LENGTH) {
        buffer = new byte[BUFFER_LENGTH];
        do {
          bytes.get(buffer);
          out.write(buffer);
        } while (bytes.remaining() >= BUFFER_LENGTH);
      } else {
        buffer = new byte[bytes.remaining()];
      }
  
      int remaining = bytes.remaining();
      if (remaining > 0) {
        bytes.get(buffer, 0, remaining);
        out.write(buffer, 0, remaining);
      }
    }
docs: Writes the contents of a <code>ByteBuffer</code> to the provided
  <code>OutputStream</code>.
  @param bytes The <code>ByteBuffer</code> containing the bytes to
  write.
  @param out The <code>OutputStream</code> to write to.
  @throws IOException If unable to write to the
  <code>OutputStream</code>.