public static boolean copyFile ( final File src , final File dest , long extent , final boolean overwrite ) throws FileNotFoundException , IOException { boolean result = false ; if ( LOGGER . isLoggable ( Level . FINE ) ) { LOGGER . fine ( "Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest . exists ( ) ) ; } if ( dest . exists ( ) ) { if ( overwrite ) { dest . delete ( ) ; LOGGER . finer ( dest . getAbsolutePath ( ) + " removed before copy." ) ; } else { // Already in place and we're not to overwrite. Return. return result ; } } FileInputStream fis = null ; FileOutputStream fos = null ; FileChannel fcin = null ; FileChannel fcout = null ; try { // Get channels fis = new FileInputStream ( src ) ; fos = new FileOutputStream ( dest ) ; fcin = fis . getChannel ( ) ; fcout = fos . getChannel ( ) ; if ( extent < 0 ) { extent = fcin . size ( ) ; } // Do the file copy long trans = fcin . transferTo ( 0 , extent , fcout ) ; if ( trans < extent ) { result = false ; } result = true ; } catch ( IOException e ) { // Add more info to the exception. Preserve old stacktrace. // We get 'Invalid argument' on some file copies. See // http://intellij.net/forums/thread.jsp?forum=13&thread=63027&message=853123 // for related issue. String message = "Copying " + src . getAbsolutePath ( ) + " to " + dest . getAbsolutePath ( ) + " with extent " + extent + " got IOE: " + e . getMessage ( ) ; if ( ( e instanceof ClosedByInterruptException ) || ( ( e . getMessage ( ) != null ) && e . getMessage ( ) . equals ( "Invalid argument" ) ) ) { LOGGER . severe ( "Failed copy, trying workaround: " + message ) ; workaroundCopyFile ( src , dest ) ; } else { IOException newE = new IOException ( message ) ; newE . initCause ( e ) ; throw newE ; } } finally { // finish up if ( fcin != null ) { fcin . close ( ) ; } if ( fcout != null ) { fcout . close ( ) ; } if ( fis != null ) { fis . close ( ) ; } if ( fos != null ) { fos . close ( ) ; } } return result ; }
Copy up to extent bytes of the source file to the destination