MLi
10/13/2019 - 12:32 AM

watchservice

public void watchservice()
{
    Thread fileWatcher = new Thread(() ->
    {
        Path path = Paths.get(rootDir+"InputFiles/"+dirName+"/request");
        Path dataDir = Paths.get(path);       

        try 
        {
            WatchService watcher = dataDir.getFileSystem().newWatchService();
            dataDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

            while (true)
            {
                WatchKey watckKey;
                try
                {
                    watckKey = watcher.take();
                }
                catch (Exception e)
                {
                    logger.error("watchService interupted:", e);
                    return;
                }
                List<WatchEvent<?>> events = watckKey.pollEvents();
                for (WatchEvent<?> event : events) 
                {
                    logger.debug("Event Type : "+ event.kind()  +" , File name found :" + event.context());
                    if (event.kind() != StandardWatchEventKinds.OVERFLOW) 
                    {
                        // do your stuff
                    }
                }
            }
        }
        catch (Exception e) 
        {
            logger.error("Error: " , e);
        }
    });
    fileWatcher.setName("File-Watcher");
    fileWatcher.start();

    fileWatcher.setUncaughtExceptionHandler((Thread t, Throwable throwable) -> 
    {
        logger.error("Error ocurred in Thread " + t, throwable);
    });
}