2

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"));
Lord7even
  • 21
  • 1
  • 6
  • Did you already find an answer? I need to open a file that may be edited, and wait until it's closed after modification. There is this Desktop functionality, and there is a Runtime class which returns ref to a Process, but it does not open file in default application. I do not know, how to combine them. – fairtrax Jan 22 '21 at 09:33

2 Answers2

-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);
erickson
  • 265,237
  • 58
  • 395
  • 493
-1

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.");
}
F. Emond
  • 3
  • 3