To open a file I just created, I use this method:
// Returns true if the file is unlocked or if it becomes unlocked in the next x seconds
public static boolean isFileUnlockedWithTimeout(File file, int timeoutInSeconds) {
if (!file.exists())
// The file does not exist. So it's not locked. (Another approach could be to throw an exception...)
return true;
long endTime = System.currentTimeMillis() + 1000 * timeoutInSeconds;
while (true) {
if (file.renameTo(file)) {
// The file is not locked
return true;
}
if (System.currentTimeMillis() > endTime) {
// After the timeout
return false;
}
// Wait 1/4 sec.
try { TimeUnit.MILLISECONDS.sleep(250); } catch (InterruptedException e) {}
}
}
Applied to the initial question:
File myFile = new File("my.pdf");
if (isFileUnlockedWithTimeout(myfile, 5)) {
// File is not locked, we can open it
Desktop.getDesktop().open(myFile);
} else {
System.out.println("File is locked. Cannot open.");
}