1

I have a requirement of implementing a Watch Service on a folder. This is straight forward approach of using Java7's watch service. I have successfully done it, I am able to capture events whenever a file is created/updated/deleted on the folder where I have been watching. The problem here is it is not applicable for contents of sub folders and it is clearly written in the documentation. My requirement is to watch over contents of sub folder as well. This is not possible using the above approach unless I write a loop over all the sub folders manually and listen to each and every folder, this I think leads to some memory leak if not programmed well.

Hence I am going with what spring suggested in the newer release explained here This is very clear approach which I have seen for WatchService. The problem here is this will listen to only ENTRY_CREATE events i.e., only the events where we have created the file and this can be at any level. This is not working when I change the file or delete the file. How should we go ahead in this case.

public static void watchFolderTree(String pathStr)
    throws Exception
    {
        long waitTime = 10000;
        WatchServiceDirectoryScanner scanner = new WatchServiceDirectoryScanner(pathStr);       
        scanner.start();
        List<File> changedFiles = null;
        while(true)
        {
            changedFiles = scanner.listFiles(new File(pathStr));
            if(changedFiles.size() > 0)
            {
                System.out.println("There is a file ");
            }
            Thread.sleep(waitTime);
        }       
    }

References :

Community
  • 1
  • 1
Kiran Joshi
  • 746
  • 1
  • 11
  • 27
  • Probably is not the comment that you're looking for but I couldn't use Java 7 watch service on one project that I'm involved because we're using a mapped drive and we found a great library to use Directory Poller (http://jpoller.sourceforge.net/) that it solved our requirement. Might be is useful to you to have a look at it. – Gerard Ribas Oct 28 '15 at 14:36
  • Thank you Gerardribas. I will look into it :) – Kiran Joshi Oct 28 '15 at 15:09

0 Answers0