public static long copyStream ( InputStream input , OutputStream output , boolean closeStreams ) throws RuntimeException { long numBytesCopied = 0 ; int bufferSize = BUFFER_SIZE ; try { // make sure we buffer the input input = new BufferedInputStream ( input , bufferSize ) ; byte [ ] buffer = new byte [ bufferSize ] ; for ( int bytesRead = input . read ( buffer ) ; bytesRead != - 1 ; bytesRead = input . read ( buffer ) ) { output . write ( buffer , 0 , bytesRead ) ; numBytesCopied += bytesRead ; } output . flush ( ) ; } catch ( IOException ioe ) { throw new RuntimeException ( "Stream data cannot be copied" , ioe ) ; } finally { if ( closeStreams ) { try { output . close ( ) ; } catch ( IOException ioe2 ) { // what to do? } try { input . close ( ) ; } catch ( IOException ioe2 ) { // what to do? } } } return numBytesCopied ; }
Copies one stream to another optionally closing the streams .