public static void update ( final FileUpdater updater , final File destFile ) throws UpdateException { final File lockFile = new File ( destFile . getAbsolutePath ( ) + ".lock" ) ; final File newDestFile = new File ( destFile . getAbsolutePath ( ) + ".new" ) ; try { // synchronize writing to file within this jvm synchronized ( UpdateUtils . class ) { final FileChannel channel = new RandomAccessFile ( lockFile , "rw" ) . getChannel ( ) ; //acquire file lock to block external jvm (commandline) from writing to file final FileLock lock = channel . lock ( ) ; try { FileUtils . copyFileStreams ( destFile , newDestFile ) ; updater . updateFile ( newDestFile ) ; if ( newDestFile . isFile ( ) && newDestFile . length ( ) > 0 ) { moveFile ( newDestFile , destFile ) ; } else { throw new UpdateException ( "Result file was empty or not present: " + newDestFile ) ; } } catch ( FileUpdaterException e ) { throw new UpdateException ( e ) ; } finally { lock . release ( ) ; channel . close ( ) ; } } } catch ( IOException e ) { throw new UpdateException ( "Unable to get and write file: " + e . toString ( ) , e ) ; } }
Update a destination file with an updater implementation while maintaining appropriate locks around the action and file