Java 类java.nio.file.WatchService 实例源码

项目:ZombieLib2    文件:DirWatcherService.java   
private void watch() {
    try {
        WatchService watchService = directoryPath.getFileSystem().newWatchService();
        directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
        while (true) {
            WatchKey watchKey = watchService.take();
            for (final WatchEvent<?> event : watchKey.pollEvents()) {
                takeActionOnChangeEvent(event);
            }
        }

    } catch (InterruptedException interruptedException) {
        System.out.println("Thread got interrupted:" + interruptedException);
    } catch (Exception exception) {
        exception.printStackTrace();
    }

}
项目:SuitAgent    文件:PluginPropertiesWatcher.java   
@Override
public void run() {
    WatchService watchService = WatchServiceUtil.watchModify(pluginDir);
    WatchKey key;
    while (watchService != null){
        try {
            key = watchService.take();
            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                if(watchEvent.kind() == ENTRY_MODIFY){
                    String fileName = watchEvent.context() == null ? "" : watchEvent.context().toString();
                    Plugin plugin = PluginLibraryHelper.getPluginByConfigFileName(fileName);
                    if(plugin != null){
                        plugin.init(PluginLibraryHelper.getPluginConfig(plugin));
                        log.info("已完成插件{}的配置重新加载",plugin.pluginName());
                    }
                }
            }
            key.reset();
        } catch (Exception e) {
            log.error("插件配置文件监听异常",e);
            break;
        }
    }
}
项目:neoscada    文件:BaseWatcher.java   
public StorageWatcher ( final StorageManager storageManager, final BaseWatcher baseWatcher, final Path path, final WatchService watcher ) throws IOException
{
    this.storageManager = storageManager;
    this.baseWatcher = baseWatcher;
    this.watcher = watcher;
    this.path = path;

    this.key = path.register ( watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY );
    baseWatcher.addWatcherMap ( path, this );

    final File nativeDir = new File ( path.toFile (), "native" );
    baseWatcher.addWatcherMap ( nativeDir.toPath (), this );

    logger.debug ( "Checking native dir: {}", nativeDir );

    if ( nativeDir.exists () && nativeDir.isDirectory () )
    {
        this.nativeKey = nativeDir.toPath ().register ( this.watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE );
        check ();
    }
}
项目:UDE    文件:UFM.java   
private static void setWatcherOnThemeFile() {
    try {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        while (true) {
            final WatchKey wk = watchService.take();
            for (WatchEvent<?> event : wk.pollEvents()) {
                //we only register "ENTRY_MODIFY" so the context is always a Path.
                final Path changed = (Path) event.context();
                System.out.println(changed);
                if (changed.endsWith("Theme.css")) {
                    System.out.println("Theme.css has changed...reloading stylesheet.");
                    scene.getStylesheets().clear();
                    scene.getStylesheets().add("resources/Theme.css");
                }
            }
            boolean valid = wk.reset();
            if (!valid)
                System.out.println("Watch Key has been reset...");
        }
    } catch (Exception e) { /*Thrown to void*/ }
}
项目:Photato    文件:PhotatoFilesManager.java   
public PhotatoFilesManager(Path rootFolder, FileSystem fileSystem, IMetadataAggregator metadataGetter, IThumbnailGenerator thumbnailGenerator, IFullScreenImageGetter fullScreenImageGetter, boolean prefixOnlyMode, boolean indexFolderName, boolean useParallelPicturesGeneration) throws IOException {
    this.fileSystem = fileSystem;
    this.metadataAggregator = metadataGetter;
    this.thumbnailGenerator = thumbnailGenerator;
    this.fullScreenImageGetter = fullScreenImageGetter;
    this.rootFolder = new PhotatoFolder(rootFolder, rootFolder);
    this.searchManager = new SearchManager(prefixOnlyMode, indexFolderName);
    this.albumsManager = new AlbumsManager();
    this.prefixOnlyMode = prefixOnlyMode;
    this.useParallelPicturesGeneration = useParallelPicturesGeneration;

    WatchService watcher = this.fileSystem.newWatchService();
    this.watchedDirectoriesKeys = new HashMap<>();
    this.watchedDirectoriesPaths = new HashMap<>();
    this.runInitialFolderExploration(watcher, this.rootFolder);
    this.watchServiceThread = new WatchServiceThread(watcher);
    this.watchServiceThread.start();
}
项目:util4j    文件:FileMonitorJdkImpl.java   
public void simpleTest(Path path) throws Exception
{
    WatchService watchService=FileSystems.getDefault().newWatchService();  
    path.register(watchService,   
            StandardWatchEventKinds.ENTRY_CREATE,  
            StandardWatchEventKinds.ENTRY_DELETE,  
            StandardWatchEventKinds.ENTRY_MODIFY);  
    while(true)  
    {  
        WatchKey watchKey=watchService.take();  
           List<WatchEvent<?>> watchEvents = watchKey.pollEvents();  
           for(WatchEvent<?> event : watchEvents){  
               //TODO 根据事件类型采取不同的操作。。。。。。。  
               System.out.println("["+event.context()+"]文件发生了["+event.kind()+"]事件");    
           }  
           watchKey.reset(); 
    } 
}
项目:jdk8u-jdk    文件:LotsOfCancels.java   
public static void main(String[] args) throws Exception {

        // create a bunch of directories. Create two tasks for each directory,
        // one to bash on cancel, the other to poll the events
        ExecutorService pool = Executors.newCachedThreadPool();
        try {
            Path top = Files.createTempDirectory("work");
            top.toFile().deleteOnExit();
            for (int i=1; i<=16; i++) {
                Path dir = Files.createDirectory(top.resolve("dir-" + i));
                WatchService watcher = FileSystems.getDefault().newWatchService();
                pool.submit(() -> handle(dir, watcher));
                pool.submit(() -> poll(watcher));
            }
        } finally {
            pool.shutdown();
        }

        // give thread pool lots of time to terminate
        if (!pool.awaitTermination(5L, TimeUnit.MINUTES))
            throw new RuntimeException("Thread pool did not terminate");

        if (failed)
            throw new RuntimeException("Test failed, see log for details");
    }
项目:jdk8u-jdk    文件:LotsOfCancels.java   
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:jdk8u-jdk    文件:LotsOfCancels.java   
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:openjdk-jdk10    文件:LotsOfCloses.java   
/**
 * Create a WatchService to watch for changes in the given directory
 * and then attempt to close the WatchService and change a registration
 * at the same time.
 */
static void test(Path dir, ExecutorService pool) throws Exception {
    WatchService watcher = FileSystems.getDefault().newWatchService();

    // initial registration
    dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

    // submit tasks to close the WatchService and update the registration
    Future<Void> closeResult;
    Future<Boolean> registerResult;

    if (RAND.nextBoolean()) {
        closeResult = pool.submit(newCloserTask(watcher));
        registerResult = pool.submit(newRegisterTask(watcher, dir));
    } else {
        registerResult = pool.submit(newRegisterTask(watcher, dir));
        closeResult = pool.submit(newCloserTask(watcher));
    }

    closeResult.get();
    registerResult.get();

}
项目:openjdk-jdk10    文件:LotsOfCancels.java   
public static void main(String[] args) throws Exception {

        // create a bunch of directories. Create two tasks for each directory,
        // one to bash on cancel, the other to poll the events
        ExecutorService pool = Executors.newCachedThreadPool();
        try {
            Path testDir = Paths.get(System.getProperty("test.dir", "."));
            Path top = Files.createTempDirectory(testDir, "LotsOfCancels");
            for (int i=1; i<=16; i++) {
                int id = i;
                Path dir = Files.createDirectory(top.resolve("dir-" + i));
                WatchService watcher = FileSystems.getDefault().newWatchService();
                pool.submit(() -> handle(id, dir, watcher));
                pool.submit(() -> poll(id, watcher));
            }
        } finally {
            pool.shutdown();
        }

        // give thread pool lots of time to terminate
        if (!pool.awaitTermination(5L, TimeUnit.MINUTES))
            throw new RuntimeException("Thread pool did not terminate");

        if (failed)
            throw new RuntimeException("Test failed, see log for details");
    }
项目:openjdk-jdk10    文件:LotsOfCancels.java   
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(int id, Path dir, WatchService watcher) {
    System.out.printf("begin handle %d%n", id);
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            System.out.printf("WatchService %d closing ...%n", id);
            watcher.close();
            System.out.printf("WatchService %d closed %n", id);
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
    System.out.printf("end handle %d%n", id);
}
项目:openjdk-jdk10    文件:LotsOfCancels.java   
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(int id, WatchService watcher) {
    System.out.printf("begin poll %d%n", id);
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do but print
        System.out.printf("poll %d expected exception %s%n", id, expected);
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
    System.out.printf("end poll %d%n", id);
}
项目:Reinickendorf_SER316    文件:AgendaPanel.java   
/**
 * 
 * @param dirsList list of directories on the system
 * @param dir path to register directories to be read later
 * @param watcher WatchService to register paths
 * @param holdValueToKey    hashmap containing key,value (paths, project id)
 * @throws IOException
 */
private static synchronized void fileSystemTraversal(ArrayList<File> dirsList, Path dir, WatchService watcher, ConcurrentHashMap<String, String> holdValueToKey) throws IOException{
    for(int i = 0;i<dirsList.size();i++){

        dir = Paths.get(dirsList.get(i).getAbsolutePath()); //get path of selected file
        dir.register(watcher,ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY); //register directory path with watcher
        String subStr = dirsList.get(i).getAbsolutePath();
        if(windows){
            String let = subStr.substring(0,2);
            subStr = let+"\\"+"\\"+subStr.substring(3,subStr.length());
        }
        Util.debug("WatchService: Registered: "+subStr);

        String projID = (String) holdValueToKey.get(subStr);  //returns the project id if src folder path is known

        if(projID != null){
            Util.debug("WatchService: Project ID = "+projID);
            String fileAbsPath = fileChosenPaths.get(projID);
            String LOCcnt = "0";

            //pathLOCcount.put(fileAbsPath, LOCcnt);
            //allPathsForFilesWithProjID.put(projID, pathLOCcount); // <ProjID,<AbsoluteFilePath, LOC count>>
        }
    }
}
项目:nifi-minifi    文件:FileChangeIngestorTest.java   
@Before
public void setUp() throws Exception {
    mockWatchService = Mockito.mock(WatchService.class);
    notifierSpy = Mockito.spy(new FileChangeIngestor());
    mockDifferentiator = Mockito.mock(Differentiator.class);
    testNotifier = Mockito.mock(ConfigurationChangeNotifier.class);

    notifierSpy.setConfigFilePath(Paths.get(TEST_CONFIG_PATH));
    notifierSpy.setWatchService(mockWatchService);
    notifierSpy.setDifferentiator(mockDifferentiator);
    notifierSpy.setConfigurationChangeNotifier(testNotifier);

    testProperties = new Properties();
    testProperties.put(FileChangeIngestor.CONFIG_FILE_PATH_KEY, TEST_CONFIG_PATH);
    testProperties.put(FileChangeIngestor.POLLING_PERIOD_INTERVAL_KEY, FileChangeIngestor.DEFAULT_POLLING_PERIOD_INTERVAL);
}
项目:openjdk9    文件:LotsOfCloses.java   
/**
 * Create a WatchService to watch for changes in the given directory
 * and then attempt to close the WatchService and change a registration
 * at the same time.
 */
static void test(Path dir, ExecutorService pool) throws Exception {
    WatchService watcher = FileSystems.getDefault().newWatchService();

    // initial registration
    dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

    // submit tasks to close the WatchService and update the registration
    Future<Void> closeResult;
    Future<Boolean> registerResult;

    if (RAND.nextBoolean()) {
        closeResult = pool.submit(newCloserTask(watcher));
        registerResult = pool.submit(newRegisterTask(watcher, dir));
    } else {
        registerResult = pool.submit(newRegisterTask(watcher, dir));
        closeResult = pool.submit(newCloserTask(watcher));
    }

    closeResult.get();
    registerResult.get();

}
项目:openjdk9    文件:LotsOfCancels.java   
public static void main(String[] args) throws Exception {

        // create a bunch of directories. Create two tasks for each directory,
        // one to bash on cancel, the other to poll the events
        ExecutorService pool = Executors.newCachedThreadPool();
        try {
            Path top = Files.createTempDirectory("work");
            top.toFile().deleteOnExit();
            for (int i=1; i<=16; i++) {
                Path dir = Files.createDirectory(top.resolve("dir-" + i));
                WatchService watcher = FileSystems.getDefault().newWatchService();
                pool.submit(() -> handle(dir, watcher));
                pool.submit(() -> poll(watcher));
            }
        } finally {
            pool.shutdown();
        }

        // give thread pool lots of time to terminate
        if (!pool.awaitTermination(5L, TimeUnit.MINUTES))
            throw new RuntimeException("Thread pool did not terminate");

        if (failed)
            throw new RuntimeException("Test failed, see log for details");
    }
项目:openjdk9    文件:LotsOfCancels.java   
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:openjdk9    文件:LotsOfCancels.java   
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:OpenFalcon-SuitAgent    文件:PluginPropertiesWatcher.java   
@Override
public void run() {
    WatchService watchService = WatchServiceUtil.watchModify(pluginDir);
    WatchKey key;
    while (watchService != null){
        try {
            key = watchService.take();
            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                if(watchEvent.kind() == ENTRY_MODIFY){
                    String fileName = watchEvent.context() == null ? "" : watchEvent.context().toString();
                    Plugin plugin = PluginLibraryHelper.getPluginByConfigFileName(fileName);
                    if(plugin != null){
                        plugin.init(PluginLibraryHelper.getPluginConfig(plugin));
                        log.info("已完成插件{}的配置重新加载",plugin.pluginName());
                    }
                }
            }
            key.reset();
        } catch (Exception e) {
            log.error("插件配置文件监听异常",e);
            break;
        }
    }
}
项目:jdk8u_jdk    文件:LotsOfCancels.java   
public static void main(String[] args) throws Exception {

        // create a bunch of directories. Create two tasks for each directory,
        // one to bash on cancel, the other to poll the events
        ExecutorService pool = Executors.newCachedThreadPool();
        try {
            Path top = Files.createTempDirectory("work");
            top.toFile().deleteOnExit();
            for (int i=1; i<=16; i++) {
                Path dir = Files.createDirectory(top.resolve("dir-" + i));
                WatchService watcher = FileSystems.getDefault().newWatchService();
                pool.submit(() -> handle(dir, watcher));
                pool.submit(() -> poll(watcher));
            }
        } finally {
            pool.shutdown();
        }

        // give thread pool lots of time to terminate
        if (!pool.awaitTermination(5L, TimeUnit.MINUTES))
            throw new RuntimeException("Thread pool did not terminate");

        if (failed)
            throw new RuntimeException("Test failed, see log for details");
    }
项目:jdk8u_jdk    文件:LotsOfCancels.java   
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:jdk8u_jdk    文件:LotsOfCancels.java   
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:LotsOfCancels.java   
public static void main(String[] args) throws Exception {

        // create a bunch of directories. Create two tasks for each directory,
        // one to bash on cancel, the other to poll the events
        ExecutorService pool = Executors.newCachedThreadPool();
        try {
            Path top = Files.createTempDirectory("work");
            top.toFile().deleteOnExit();
            for (int i=1; i<=16; i++) {
                Path dir = Files.createDirectory(top.resolve("dir-" + i));
                WatchService watcher = FileSystems.getDefault().newWatchService();
                pool.submit(() -> handle(dir, watcher));
                pool.submit(() -> poll(watcher));
            }
        } finally {
            pool.shutdown();
        }

        // give thread pool lots of time to terminate
        if (!pool.awaitTermination(5L, TimeUnit.MINUTES))
            throw new RuntimeException("Thread pool did not terminate");

        if (failed)
            throw new RuntimeException("Test failed, see log for details");
    }
项目:lookaside_java-1.8.0-openjdk    文件:LotsOfCancels.java   
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:LotsOfCancels.java   
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:mssqlapplylogs    文件:Watch.java   
private Watch(final List<Path> dirs,
              final WatchService watcher,
              final Map<WatchKey, Path> keys,
              final boolean recursive) throws IOException
{
    this.watcher = watcher;
    this.keys = keys;
    this.recursive = recursive;

    if (recursive)
    {
        LOGGER.debug(String.format("Scanning '%s'...\n", dirs));

        registerAll(dirs.get(0), keys, watcher);

        LOGGER.debug("Scanning is done.\n");
    }
    else
    {
        register(dirs.get(0), keys, watcher);
    }
}
项目:mssqlapplylogs    文件:Watch.java   
private static void registerAll(final Path start,
                                final Map<WatchKey,Path> keys,
                                final WatchService watcher ) throws IOException
{
    // register directory and sub-directories
    Files.walkFileTree(start, new SimpleFileVisitor<Path>()
    {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                throws IOException
        {
            register(dir, keys, watcher);

            return FileVisitResult.CONTINUE;
        }
    });
}
项目:code-similarity    文件:FileWatchServiceDemo.java   
public static void main(String[] args) throws Throwable {
    String tempDirPath = "/tmp";
    System.out.println("Starting watcher for " + tempDirPath);
    Path p = Paths.get(tempDirPath);
    WatchService watcher = 
        FileSystems.getDefault().newWatchService();
    Kind<?>[] watchKinds = { ENTRY_CREATE, ENTRY_MODIFY };
    p.register(watcher, watchKinds);
    mainRunner = Thread.currentThread();
    new Thread(new DemoService()).start();
    while (!done) {
        WatchKey key = watcher.take();
        for (WatchEvent<?> e : key.pollEvents()) {
            System.out.println(
                "Saw event " + e.kind() + " on " + 
                e.context());
            if (e.context().toString().equals("MyFileSema.for")) {
                System.out.println("Semaphore found, shutting down watcher");
                done = true;
            }
        }
        if (!key.reset()) {
            System.err.println("Key failed to reset!");
        }
    }
}
项目:spike.x    文件:NioDirWatcher.java   
public void watch(
        final Path dir,
        final Kind<Path>[] kinds) throws IOException {

    WatchService service = FileSystems.getDefault().newWatchService();
    // Rationale for SensitivityWatchEventModifier.HIGH: 
    // http://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-else
    dir.register(
            service,
            kinds,
            SensitivityWatchEventModifier.HIGH);

    m_logger.info("Watching directory: {}", dir);
    m_watcher = new WatcherThread(service, m_eventBus);
    m_watcher.start(); // Start watcher thread
}
项目:training    文件:FileWatchService.java   
public static void main(String[] args) throws IOException, InterruptedException {
    Path tmpDir = Paths.get("tmp");
    WatchService watchService = FileSystems.getDefault().newWatchService();
    Path monitoredFolder = tmpDir;
    monitoredFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);

    tmpDir.toFile().mkdirs();
    new FileChanger(tmpDir).start();
    while (true) {
        System.out.println("Waiting for event");
        WatchKey watchKey = watchService.take();
        for (WatchEvent<?> event : watchKey.pollEvents()) {
            System.out.println("Detected event " + event.kind().name() + " on file " + event.context().toString());
        }
        watchKey.reset();
    }
}
项目:Kvantum    文件:FileWatcher.java   
private FileWatchingContext(final Path path,
                            final WatchService service,
                            final BiConsumer<Path, WatchEvent.Kind<?>> reaction)
        throws IllegalArgumentException
{
    if ( path == null )
    {
        throw new IllegalArgumentException( "Supplied path was null" );
    }
    if ( service == null )
    {
        throw new IllegalArgumentException( "Supplied watch service was null" );
    }
    this.path = path;
    this.watchService = service;
    if ( reaction == null )
    {
        this.reaction = (file, kind) -> {
        };
    } else
    {
        this.reaction = reaction;
    }
}
项目:maker    文件:WatchServiceTest.java   
public static void main(String[] args) throws Exception  
{  

    WatchService watchService=FileSystems.getDefault().newWatchService();  
    Paths.get("C:/").register(watchService,   
            StandardWatchEventKinds.ENTRY_CREATE,  
            StandardWatchEventKinds.ENTRY_DELETE,  
            StandardWatchEventKinds.ENTRY_MODIFY);  
    while(true)  
    {  
        WatchKey key=watchService.take();  
        for(WatchEvent<?> event:key.pollEvents())  
        {  
            System.out.println(event.context()+"发生了"+event.kind()+"事件");  
        }  
        if(!key.reset())  
        {  
            break;  
        }  
    }
}
项目:LogAnalyzer    文件:Test.java   
private static void watch() throws Exception
{
    WatchService watchService=FileSystems.getDefault().newWatchService();
    Paths.get("C:/").register(watchService, 
            StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.OVERFLOW);

    while(true)
    {
        WatchKey key=watchService.take();
        //watchService.poll(10000, TimeUnit.valueOf("2014-8-26"));
        for(WatchEvent<?> event:key.pollEvents())
        {
            System.out.println(event.context()+"发生了"+event.kind()+"事件"+event.count());
        }
        if(!key.reset())
        {
            break;
        }
    }
}
项目:blynk-server    文件:FileChangeWatcherWorker.java   
@Override
public void run() {
    try {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        propsFileFolder.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        while (true) {
            WatchKey wk = watchService.take();
            for (WatchEvent<?> event : wk.pollEvents()) {
                Path changed = (Path) event.context();
                Path changedFile = propsFileFolder.resolve(changed.toString());
                if (changed.getFileName().toString().endsWith(fileName) && Files.exists(changedFile)) {
                    log.info("File '{}' changed. Updating values.", changedFile);
                    limits.tokenBody = FileLoaderUtil.readFileAsString(fileName);
                }
            }
            // reset the key
            boolean valid = wk.reset();
            if (!valid) {
                log.info("Key has been not unregistered.");
            }
        }
    } catch (IOException | InterruptedException e) {
        log.warn("Error monitoring '{}' file. Reloadable properties are not enabled.",
                SERVER_PROPERTIES_FILENAME, e);
    }
}
项目:ephemeralfs    文件:WatchServiceTest.java   
@Test
public void testRegisterNonDirectory() throws IOException, Exception {

    Path file = root.resolve("file");
    Files.createFile(file);


    try(WatchService service = root.getFileSystem().newWatchService()) {
        try
        {
            file.register(service, StandardWatchEventKinds.ENTRY_MODIFY);
            fail();
        } catch(NotDirectoryException e) {
            //pass
        }
    }

}
项目:ephemeralfs    文件:WatchServiceTest.java   
@Test
public void testRegisterDirDoesNotExist() throws IOException, Exception {

    Path dir = root.resolve("dir");


    try(WatchService service = root.getFileSystem().newWatchService()) {
        try
        {
            dir.register(service, StandardWatchEventKinds.ENTRY_MODIFY);
            fail();
        } catch(NoSuchFileException e) {
            //pass
        }
    }

}
项目:ephemeralfs    文件:WatchServiceTest.java   
@Test
public void testSeeNewChildren() throws IOException, Exception {
    try(WatchService service = root.getFileSystem().newWatchService()) {
        assertNotNull(root.register(service, StandardWatchEventKinds.ENTRY_CREATE));

        Files.createFile(root.resolve("test"));

        WatchKey key = poll(service);
        assertNotNull(key);

        List<WatchEvent<?>> events = key.pollEvents();

        assertEquals(1, events.size());
        assertEquals(1, events.get(0).count());
        assertEquals(StandardWatchEventKinds.ENTRY_CREATE, events.get(0).kind());
        assertEquals(root.resolve("test").getFileName(), events.get(0).context());

        assertTrue(key.pollEvents().isEmpty());

        assertTrue(key.reset());
    }
}
项目:ephemeralfs    文件:WatchServiceTest.java   
@Test
public void testReRegisterAfterDirDeletedCreated() throws IOException, Exception {
    Path dir = root.resolve("dir");
    Files.createDirectories(dir);
    try(WatchService service = root.getFileSystem().newWatchService()) {

        assertNotNull(dir.register(service, StandardWatchEventKinds.ENTRY_CREATE));

        Files.createFile(dir.resolve("test"));

        WatchKey key = poll(service);
        assertNotNull(key);

        List<WatchEvent<?>> events = key.pollEvents();

        assertEquals(1, events.size());
        assertEquals(1, events.get(0).count());
        assertEquals(StandardWatchEventKinds.ENTRY_CREATE, events.get(0).kind());

        TestUtil.deleteTempDirRecursive(dir);
        Files.createDirectories(dir);

        assertKeyDoesNotReset(key);
    }

}
项目:ephemeralfs    文件:WatchServiceTest.java   
@Test
public void testResetDirDoesNotExist() throws IOException, Exception {

    Path child = root.resolve("child");
    Files.createDirectories(child);

    try(WatchService service = child.getFileSystem().newWatchService()) {
        child.register(service, StandardWatchEventKinds.ENTRY_CREATE);

        Files.createFile(child.resolve("test"));

        WatchKey key = poll(service);
        assertNotNull(key);
        key.pollEvents();

        TestUtil.deleteTempDirRecursive(child);
        assertKeyDoesNotReset(key);
    }

}