My Java program wants to read a file which can be locked by another program writing into it. I need to check if the file is locked and if so wait until it is free. How do I achieve this?
The Java program is running on a Windows 2000 server.
My Java program wants to read a file which can be locked by another program writing into it. I need to check if the file is locked and if so wait until it is free. How do I achieve this?
The Java program is running on a Windows 2000 server.
I tryed combination of answers (@vlad) on windows with access to Linux Smb share and it worked for me. The first part was enough for lock like Excel but not for some editors. I added second part (rename) for testing both situations.
public static boolean testLockFile(File p_fi) {
boolean bLocked = false;
try (RandomAccessFile fis = new RandomAccessFile(p_fi, "rw")) {
FileLock lck = fis.getChannel().lock();
lck.release();
} catch (Exception ex) {
bLocked = true;
}
if (bLocked)
return bLocked;
// try further with rename
String parent = p_fi.getParent();
String rnd = UUID.randomUUID().toString();
File newName = new File(parent + "/" + rnd);
if (p_fi.renameTo(newName)) {
newName.renameTo(p_fi);
} else
bLocked = true;
return bLocked;
}
For Windows, you can also use:
new RandomAccessFile(file, "rw")
If the file is exclusively locked (by MS Word for example), there will be exception:
java.io.FileNotFoundException: <fileName> (The process cannot access the file because it is being used by another process).
This way you do not need to open/close streams just for the check.
Note - if the file is not exclusively locked (say opened in Notepad++) there will be no exception.
Improved Amjad Abdul-Ghani answer, I found that no error was produced until attempting to read from the file
public static boolean isFilelocked(File file) {
try {
try (FileInputStream in = new FileInputStream(file)) {
in.read();
return false;
}
} catch (FileNotFoundException e) {
return file.exists();
} catch (IOException ioe) {
return true;
}
}