Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WatchService locks some files?

Tags:

java

nio

I'm using java.nio WatchService to watch the filesystem for changes (for a webapp syncing project).

However, when I clean the watched directory, I get a problem that a files is in use (in fact, I'm cleaning with maven, and maven complains it can't clean everything). That would imply that the WatchService somehow locks the watched resources.

How to watch a directory without any locking/disallowing deletion?

like image 918
Bozho Avatar asked Nov 11 '22 18:11

Bozho


1 Answers

I have been using Apache Commons VFS2 for this purpose for long time without any issues in any OS. Basically you need a class to implement FileListener interface that lets you do actions when adding/updating/deleting files from a directory:

public interface FileListener {
    /**
     * Called when a file is created.
     */
    void fileCreated(FileChangeEvent event) throws Exception;

    /**
     * Called when a file is deleted.
     */
    void fileDeleted(FileChangeEvent event) throws Exception;

    /**
     * Called when a file is changed.
     */
    void fileChanged(FileChangeEvent event) throws Exception;
}

More info: Link to FileListener

Then you need to start the monitor for that file listener. Here you have an untested snippet on how to do it:

private void startMonitor() {
    Logger logger = LogManager.getLogger(MyClass.class);
    try {
        FileSystemManager fileSystemManager = VFS.getManager();
        FileObject dirToWatchFO = null;
        String path = "dir/you/want/to/watch";

        File pathFile = new File(path);
        path = pathFile.getAbsolutePath();
        dirToWatchFO = fileSystemManager.resolveFile(path);

        DefaultFileMonitor fileMonitor = new DefaultFileMonitor(new MyFancyFileListener());
        fileMonitor.setRecursive(false);
        fileMonitor.addFile(dirToWatchFO);
        fileMonitor.start();
    } catch (FileSystemException e) {
        logger.error("SOMETHING WENT WRONG!!", e);
    }
}

I hope it helps!

like image 59
hveiga Avatar answered Nov 15 '22 11:11

hveiga