我正在寻找一个解决方案,直到文件被打开。我的应用程序打开pdf文件并显示用户输入对话框,但对话框与pdf文件重叠。有没有一种方法可以添加一个监听器或其他东西来显示我的对话框,当pdf文件完全打开?
我可以使用延迟或暂停,但这不是我想要的。
我用
Desktop.getDesktop().open(new File("my.pdf"));
如果您知道桌面打开PDF文件所需的时间,则可以使用定时器。
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);
打开刚刚创建的文件,使用以下方法:
// 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.");
}