code: public static void byteBufferToOutputStream(ByteBuffer in, OutputStream out)
        throws IOException {
      final int BUF_SIZE = 8192;
  
      if (in.hasArray()) {
        out.write(in.array(), in.arrayOffset() + in.position(), in.remaining());
      } else {
        final byte[] b = new byte[Math.min(in.remaining(), BUF_SIZE)];
        while (in.remaining() > 0) {
          int bytesToRead = Math.min(in.remaining(), BUF_SIZE);
          in.get(b, 0, bytesToRead);
  
          out.write(b, 0, bytesToRead);
        }
      }
    }
docs: Reads the full contents of a ByteBuffer and writes them to an OutputStream. The ByteBuffer is
  consumed by this operation; eg in.remaining() will be 0 after it completes successfully.
  @param in  ByteBuffer to write into the OutputStream
  @param out Destination stream
  @throws IOException If there is an error writing into the OutputStream