Search code examples
javawindowscmdsystemwatchservice

How i can make a Watch Service that deletes a file when it closes?


I basically want to make a watch service (or something like it) that checks if a file has been closed and instantly remove that file if it did close(finished executing).

How I can achieve this? please give me a cmd commands or some code(i prefer Java).


Solution

  • Ok, this should not be hard to do, if you google a bit you find a Java-File Method called file.canWrite() which basically returns if a file is locked by an other program or so.

    So codewise what you could do is something like this.

    boolean isDeleted = false;
    File f = new File (// Put your file here);
    while (!isDeleted) {
        if (f.canWrite()) {
            f.delete();
            isDeleted = true;
        } else {
            try {
                Thread.sleep(10); // Throws Exception you need to catch somewhere...
            } catch (Exception e) {}
        }
    }
    

    This code you need to include into some Java-Program. I added a simple Thread.sleep(10) that your PC does not have to check aaaaaalllllllll the time. See Check if a file is locked in Java

    Other possibility would be trying to rename the file with file.renameTo("some_path.txt"); as this method also returns a boolean whether it was successfull! Just note that you then need to update the file again before removing it.

    Last possibility I see is pretty similar to the second one. You try to delete the file by calling file.delete(); If the file still exists you know it was not successful and loop because of that.