0

Is there any way to detect if a file has been opened/close, by any application? I want to delete a file as soon as it has been released (closed) by an external editor. I am looking specifically for "opened" and "closed" events, which are not provided by WatchServices.

I thought about scanning processes for specific names (e.g., "Word", "Excel", etc.), but if find one, I need to somehow find what exact files are opened by these processes.

CorellianAle
  • 645
  • 8
  • 16
  • If it is windows environment then this will helpful https://stackoverflow.com/a/16385462/1423818 – mallikarjun Nov 01 '18 at 10:58
  • hmmm but if you try to delete it while its open by another application wont it fail? and thus isnt the failure to delete an indication that the file is being used atm? – Sir. Hedgehog Nov 01 '18 at 11:01
  • @Sir.Hedgehog I intend to scan for file `isOpened` state and execute my event handler once `isOpened == false`. I believe doing something like `while (true) { if (tryDelete(file)) break; }` would not be very efficient and a better way exist. Besides, if `tryDelete(file)` succedes, I would no longer be able to manipulate the file (before it's deletion) because it would already be deleted. – CorellianAle Nov 01 '18 at 11:09
  • you can make a "listener", so you wont end up in a loop. and when the file is available then you can do to it anything you want before you delete it. dunno what isOpened does as you didnt paste any code. so i can only assume here. – Sir. Hedgehog Nov 01 '18 at 11:20
  • @Sir.Hedgehog What "listener", it still has to poll for changes as I understand. Can you explain a bit? – CorellianAle Nov 01 '18 at 12:28

1 Answers1

0

I did this, to check if an excel is opened, you can do something similar.

public static boolean isFileAlreadyOpened(String fileName) {

    File file = new File(fileName);
    Workbook workBook = null;
    try {
        workBook = WorkbookFactory.create(file);
        workBook.close();
        return Boolean.FALSE;

    } catch (Exception e) {
        return Boolean.TRUE;
    }
}

May be you can have a Thread with timer that keeps on checking this at some specific interval. If the file is found to be not opened. You can delete the file.

Cheers !!!