I am making a program in java that monitors and backs up a directory. From time to time I have to upload modified files to the repository or upload if there is a new version. To do this, I need to lock the file so that the user cannot modify the contents or delete it. I am currently using this code to lock a file:
file = new RandomAccessFile("C:\\Temp\\report.txt", "rw");
FileChannel fileChannel = file.getChannel();
fileLock = fileChannel.tryLock();
if (fileLock != null) {
System.out.println("File is locked");
try{
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
else{
System.out.println("Failed");
}
} catch (FileNotFoundException e) {
System.out.println("Failed");
}finally{
if (fileLock != null){
fileLock.release();
}
However, if there is a new version, I need to delete the old file and replace it with the new one. But locking the file does not allow me to delete the file.
Should I unlock and delete it for writing, believing that the user will not write to the file? Or is there any other way to do this?
source
share