本文整理汇总了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();
}
}
示例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;
}
}
}
示例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 ();
}
}
示例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*/ }
}
示例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();
}
示例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();
}
}
示例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");
}
示例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;
}
}
示例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;
}
}
示例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();
}
示例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");
}
示例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);
}
示例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);
}
示例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>>
}
}
}
示例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);
}