Search code examples
javafilesystemdesktoppid

How can I open a file and notify when it is closed in Java?


My question is clear I think, is it possible to open a file automatically according to its extension then when it's closed get notify?

I try to open file with this way:

File f = new File(url);
Desktop.getDesktop().open(f);

But I can't get notification when the file closed, is there any alternative for that?


Solution

  • You can try to look at WatchService API

    The WatchService API is designed for applications that need to be notified about file change events.

    You can also check if your file is closed or not like this using Apache:

    boolean open = false;
    try
    {
      org.apache.commons.io.FileUtils.touch(myFile);
      open = true;
    }
    catch
    {   
        open = false;
    }
    
    if(open == false){
        // Show notification message.
    }