I would like to copy a file and replace the existing file. The problem is that if the file is in use by another program, an AccessDeniedException occurs, and the existing file is deleted. I would like the existing file to be retained if the copy fails. The following code demonstrates the problem. (Note this problem was also reported in Java Files.copy replace existing deletes file entirely but the OP did not provide a way to reproduce the problem.)
public void copyFile(){
Path workingCopy = null;
//Create a plain text file called example-file-error.txt, add some text to the file, and save it in user.home
Path path = Paths.get(System.getProperty("user.home"), "example-file-error.txt");
try{
workingCopy = Files.createTempFile(path.getParent(), "temp", ".txt");
//Create a locked file, but the lock is actually created by a separate program
FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ);
FileLock lock = fileChannel.lock(0, Long.MAX_VALUE, true);
Files.copy(workingCopy, path, StandardCopyOption.REPLACE_EXISTING);
}catch(Exception ex){
ex.printStackTrace();
}finally{
try{
Files.deleteIfExists(workingCopy);
}catch(IOException ex){
ex.printStackTrace();
}
}
}
Is there a way to retain the original file if the copy fails? Or, is there a way to wait for access to a file before trying to make a copy?