I’m making a program in java that monitors and backup a directory. From time to time I have to upload modified files to the repository or download if there is a new version of it.
In order to do this I have to lock the file so that the user is unable to change the contents or delete it.
Currently I’m using this code to lock the 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{
//Do what i need
}catch (Exception e){//Catch exception if any
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 have to delete the old file and replace with new one.
But File lock does not allow me to delete the file.
Should I unlock and delete it write away, trusting that the user wont write in file? Or is there any other way of doing this?
You could truncate the file:
and afterwards write the new version over it, this wouldn’t create the time gap in which the user can create the file again.
From documentation:
http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#truncate%28long%29