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:
fileChannel.truncate(0);
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:
If the given size is less than the file's current size then the file is truncated, discarding any bytes beyond the new end of the file. If the given size is greater than or equal to the file's current size then the file is not modified. In either case, if this channel's file position is greater than the given size then it is set to that size.
http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#truncate%28long%29
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With