问题
I'm searching for a solution to wait until a file is opened. My application opens pdf files and displays user-input dialogs but the dialog is overlapped by the pdf file. Is there a way to add a listener or something to show my dialog when the pdf file is fully open?
I could use a delay or pause but that's not exactly what I want.
I'm using
Desktop.getDesktop().open(new File("my.pdf"));
回答1:
You can instead use a Timer, if you know the time the desktop would take to open the PDF file.
import java.util.Timer;
...
Timer timer = new Timer();
...
Desktop.getDesktop().open(new File("my.pdf"));
int openTime = 10*1000; //Let's say it would take 10s to be opened
timer.schedule(new TimerTask() {
@Override
public void run() {
//Code to show the dialog you need
}
}, openTime);
回答2:
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.");
}
来源:https://stackoverflow.com/questions/38074647/java-desktop-getdesktop-open-wait-until-file-is-open