Here you can find the source of copyFileLocking(File copyFrom, File copyTo)
public static boolean copyFileLocking(File copyFrom, File copyTo) throws FileNotFoundException, IOException
//package com.java2s; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; public class Main { public static boolean copyFileLocking(File copyFrom, File copyTo) throws FileNotFoundException, IOException { if ((!(copyFrom.exists())) || (copyTo == null)) { return false; }//from w ww.ja v a 2 s . c o m byte[] arrayOfByte = new byte[4096]; FileOutputStream fileOutput = new FileOutputStream(copyTo, true); try { FileChannel channel = fileOutput.getChannel(); FileLock fileLock = channel.tryLock(); if (fileLock != null) { channel.truncate(0L); BufferedInputStream input = new BufferedInputStream(new FileInputStream(copyFrom)); BufferedOutputStream output = new BufferedOutputStream(fileOutput); try { int i; while ((i = input.read(arrayOfByte, 0, arrayOfByte.length)) != -1) { output.write(arrayOfByte, 0, i); } output.flush(); fileLock.release(); } catch (Exception ex) { throw new RuntimeException("copyFileLocking ERR : " + ex.getMessage(), ex); } finally { output.close(); input.close(); } return true; } } catch (Exception ex) { throw new RuntimeException("copyFileLocking ERR : " + ex.getMessage(), ex); } finally { fileOutput.close(); } throw new IOException("Unable to acquire file lock for " + copyTo); } }