Java - Desktop.getDesktop()。open() - 等到文件打开?

时间:2016-06-28 11:12:29

标签: java file desktop

我正在寻找一个等待文件打开的解决方案。我的应用程序打开pdf文件并显示用户输入对话框,但对话框与pdf文件重叠。当pdf文件完全打开时,有没有办法添加一个监听器或什么来显示我的对话框?

我可以使用延迟或暂停,但这不完全是我想要的。

我正在使用

Desktop.getDesktop().open(new File("my.pdf"));

2 个答案:

答案 0 :(得分:0)

如果您知道桌面打开PDF文件所需的时间,则可以使用Timer

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);

答案 1 :(得分:0)

要打开我刚刚创建的文件,请使用以下方法:

// 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) {}
    }
}

适用于第一个问题:

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.");
}