public static void downloadFile ( URL url , File destination ) throws IOException { int count = 0 ; int maxTries = 10 ; int timeout = 60000 ; //60 sec File tempFile = File . createTempFile ( getFilePrefix ( destination ) , "." + getFileExtension ( destination ) ) ; // Took following recipe from stackoverflow: // http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java // It seems to be the most efficient way to transfer a file // See: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html ReadableByteChannel rbc = null ; FileOutputStream fos = null ; while ( true ) { try { URLConnection connection = prepareURLConnection ( url . toString ( ) , timeout ) ; connection . connect ( ) ; InputStream inputStream = connection . getInputStream ( ) ; rbc = Channels . newChannel ( inputStream ) ; fos = new FileOutputStream ( tempFile ) ; fos . getChannel ( ) . transferFrom ( rbc , 0 , Long . MAX_VALUE ) ; break ; } catch ( SocketTimeoutException e ) { if ( ++ count == maxTries ) throw e ; } finally { if ( rbc != null ) { rbc . close ( ) ; } if ( fos != null ) { fos . close ( ) ; } } } logger . debug ( "Copying temp file {} to final location {}" , tempFile , destination ) ; copy ( tempFile , destination ) ; // delete the tmp file tempFile . delete ( ) ; }
Download the content provided at URL url and store the result to a local file using a temp file to cache the content in case something goes wrong in download