public static boolean copy ( File sourceFile , File targetFile , boolean overwrite ) throws FileAlreadyExistsException , IOException { boolean overwriteOccurred = false ; // check if the targetFile already exists if ( targetFile . exists ( ) ) { // if overwrite is not allowed, throw an exception if ( ! overwrite ) { throw new FileAlreadyExistsException ( "Target file " + targetFile + " already exists" ) ; } else { // set the flag that it occurred overwriteOccurred = true ; } } // proceed with copy FileInputStream fis = new FileInputStream ( sourceFile ) ; FileOutputStream fos = new FileOutputStream ( targetFile ) ; fis . getChannel ( ) . transferTo ( 0 , sourceFile . length ( ) , fos . getChannel ( ) ) ; fis . close ( ) ; fos . flush ( ) ; fos . close ( ) ; return overwriteOccurred ; }
Copy the source file to the target file while optionally permitting an overwrite to occur in case the target file already exists .