But how do you ensure that only one process is editing files in a directory. (I forgot to mention that it is not only editing. I also create and delete files in the directory).
I thought about using a lock-file. But is that safe?
private File sharedLockFile = new File("lockfile.lock");
private FileChannel channel;
private FileLock lock;
public void editFiles() {
try {
while(!lockFile()) {
Tread.sleep(200);
}
//Create, Delete and Edit files in a directory used by other applications
} finally {
unlockFile()
}
}
private boolean lockFile() throws IOException {
// Check if the lock exist
if (sharedLockFile.exists())
// if exist try to delete it
sharedLockFile.delete();
// Try to get the lock
channel = new RandomAccessFile(sharedLockFile, "rw").getChannel();
lock = channel.tryLock();
if (lock == null) {
// File is locked by other application
channel.close();
return false;
}
return true;
}
public static void unlockFile() throws IOException {
// release and delete file lock
try {
if (lock != null) {
lock.release();
channel.close();
}
finally {
if (sharedLockFile != null)
sharedLockFile.delete();
}
}
I appreciate the help even if it does not have anything to do with Java Chronicle. You can remove my posts from this Group later if you wan't to.