public static int writeByteBufferToStream(OutputStream out,ByteBuffer outBuf,ByteBuffer inBuf) throws IOException {
  int bytesToWrite=inBuf.remaining();
  if (bytesToWrite > 0) {
    if (inBuf.hasArray()) {
      flushStream(out,outBuf);
      out.write(inBuf.array(),inBuf.arrayOffset() + inBuf.position(),bytesToWrite);
      inBuf.position(inBuf.limit());
    }
 else {
      int bytesToWriteThisTime=bytesToWrite;
      int OUT_MAX=outBuf.remaining();
      while (bytesToWriteThisTime > OUT_MAX) {
        int oldLimit=inBuf.limit();
        inBuf.limit(inBuf.position() + OUT_MAX);
        outBuf.put(inBuf);
        inBuf.limit(oldLimit);
        flushStream(out,outBuf);
        bytesToWriteThisTime-=OUT_MAX;
        OUT_MAX=outBuf.remaining();
      }
      outBuf.put(inBuf);
    }
  }
  return bytesToWrite;
}

public static int writeByteBufferToStream ( OutputStream out , ByteBuffer outBuf , ByteBuffer inBuf ) throws IOException { int bytesToWrite = inBuf . remaining ( ) ; if ( bytesToWrite > 0 ) { if ( inBuf . hasArray ( ) ) { flushStream ( out , outBuf ) ; out . write ( inBuf . array ( ) , inBuf . arrayOffset ( ) + inBuf . position ( ) , bytesToWrite ) ; inBuf . position ( inBuf . limit ( ) ) ; } else { int bytesToWriteThisTime = bytesToWrite ; int OUT_MAX = outBuf . remaining ( ) ; while ( bytesToWriteThisTime > OUT_MAX ) { int oldLimit = inBuf . limit ( ) ; inBuf . limit ( inBuf . position ( ) + OUT_MAX ) ; outBuf . put ( inBuf ) ; inBuf . limit ( oldLimit ) ; flushStream ( out , outBuf ) ; bytesToWriteThisTime -= OUT_MAX ; OUT_MAX = outBuf . remaining ( ) ; } outBuf . put ( inBuf ) ; } } return bytesToWrite ; }
returns the number of bytes written
