I am using the Apache Commons IO:
FileUtils.copyFileToDirectory(srcFile, destDir)
How do I make Windows lock the destination file during copy? Windows locks the file correctly if I use:
Runtime.getRuntime().exec( 'cmd /c copy /Y \'' + srcFile.getCanonicalPath() + '\' \'' + destDir.getCanonicalPath() + '\'').waitFor();
Notes: The contention is not with the local program, but an external one. The file is being copied to a remote system. The remote system is processing the file before it completes the copy. Because the systems are Windows, the normal copy locks the file and blocks the external program from access.
Java doesn’t natively support file locking.
If contention for the file is coming from within your program, perhaps you need to build additional synchronization on top of the file copy to make sure concurrent writes don’t clobber one another. However, if the contention is coming from somewhere external to your software then there isn’t much you can do. You can try writing the file to a temporary directory and then renaming it since the rename is more or less atomic (depending on the filesystem).
It would help to have more information on why you need to lock the file in the first place.
In that case, you should try writing to a temporary file and then renaming it when the file is fully copied. File renames are atomic operations (on a non networked filesystem) so it should work for you.