public static long copyWithTimeout ( InputStream is , OutputStream os , long timeout ) throws IOException , TimeoutException { byte [ ] buffer = new byte [ DEFAULT_BUFFER_SIZE ] ; int n ; long startTime = System . currentTimeMillis ( ) ; long size = 0 ; while ( - 1 != ( n = is . read ( buffer ) ) ) { if ( System . currentTimeMillis ( ) - startTime > timeout ) { throw new TimeoutException ( String . format ( "Copy time has exceeded %,d millis" , timeout ) ) ; } os . write ( buffer , 0 , n ) ; size += n ; } return size ; }
Copy from the input stream to the output stream and tries to exit if the copy exceeds the timeout . The timeout is best effort . Specifically is . read will not be interrupted .