當前位置: 首頁>>代碼示例>>Java>>正文


Java WatchService類代碼示例

本文整理匯總了Java中java.nio.file.WatchService的典型用法代碼示例。如果您正苦於以下問題:Java WatchService類的具體用法?Java WatchService怎麽用?Java WatchService使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


WatchService類屬於java.nio.file包,在下文中一共展示了WatchService類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: watch

import java.nio.file.WatchService; //導入依賴的package包/類
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();
    }

}
 
開發者ID:patexoid,項目名稱:ZombieLib2,代碼行數:20,代碼來源:DirWatcherService.java

示例2: run

import java.nio.file.WatchService; //導入依賴的package包/類
@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;
        }
    }
}
 
開發者ID:DevopsJK,項目名稱:SuitAgent,代碼行數:25,代碼來源:PluginPropertiesWatcher.java

示例3: StorageWatcher

import java.nio.file.WatchService; //導入依賴的package包/類
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 ();
    }
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:22,代碼來源:BaseWatcher.java

示例4: setWatcherOnThemeFile

import java.nio.file.WatchService; //導入依賴的package包/類
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*/ }
}
 
開發者ID:maximstewart,項目名稱:UDE,代碼行數:23,代碼來源:UFM.java

示例5: PhotatoFilesManager

import java.nio.file.WatchService; //導入依賴的package包/類
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();
}
 
開發者ID:trebonius0,項目名稱:Photato,代碼行數:19,代碼來源:PhotatoFilesManager.java

示例6: simpleTest

import java.nio.file.WatchService; //導入依賴的package包/類
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(); 
    } 
}
 
開發者ID:juebanlin,項目名稱:util4j,代碼行數:19,代碼來源:FileMonitorJdkImpl.java

示例7: main

import java.nio.file.WatchService; //導入依賴的package包/類
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");
    }
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:26,代碼來源:LotsOfCancels.java

示例8: handle

import java.nio.file.WatchService; //導入依賴的package包/類
/**
 * 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;
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:23,代碼來源:LotsOfCancels.java

示例9: poll

import java.nio.file.WatchService; //導入依賴的package包/類
/**
 * 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;
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:22,代碼來源:LotsOfCancels.java

示例10: test

import java.nio.file.WatchService; //導入依賴的package包/類
/**
 * 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();

}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:28,代碼來源:LotsOfCloses.java

示例11: main

import java.nio.file.WatchService; //導入依賴的package包/類
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");
    }
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:27,代碼來源:LotsOfCancels.java

示例12: handle

import java.nio.file.WatchService; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:27,代碼來源:LotsOfCancels.java

示例13: poll

import java.nio.file.WatchService; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:25,代碼來源:LotsOfCancels.java

示例14: fileSystemTraversal

import java.nio.file.WatchService; //導入依賴的package包/類
/**
 * 
 * @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>>
		}
	}
}
 
開發者ID:ser316asu,項目名稱:Reinickendorf_SER316,代碼行數:33,代碼來源:AgendaPanel.java

示例15: setUp

import java.nio.file.WatchService; //導入依賴的package包/類
@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);
}
 
開發者ID:apache,項目名稱:nifi-minifi,代碼行數:17,代碼來源:FileChangeIngestorTest.java


注:本文中的java.nio.file.WatchService類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。