下面列出了怎么用java.nio.file.WatchService的API类实例代码及写法,或者点击链接到github查看源代码。
public WatchServiceHolder(TaskServiceImpl taskServiceImpl){
logger = LoggerFactory.getLogger(getClass());
taskService = taskServiceImpl;
incurredTasks = Collections.synchronizedMap(new HashMap<WatchKey, ITaskDescriptor>());
WatchService initWatchService;
try {
initWatchService = FileSystems.getDefault().newWatchService();
} catch (IOException ioe) {
initWatchService = null;
logger.error(
"Error instantiating WatchService, filesystem events will not be picked up.", ioe);
}
watchService = initWatchService;
pollerThread = new WatchServicePoller();
}
/**
* Wait until a PubSub emulator configuration file is updated.
* Fail if the file does not update after 1 second.
* @param watchService the watch-service to poll
* @throws InterruptedException which should interrupt the peaceful slumber and bubble up
* to fail the test.
*/
private void updateConfig(WatchService watchService) throws InterruptedException {
int attempts = 10;
while (--attempts >= 0) {
WatchKey key = watchService.poll(100, TimeUnit.MILLISECONDS);
if (key != null) {
Optional<Path> configFilePath = key.pollEvents().stream()
.map((event) -> (Path) event.context())
.filter((path) -> ENV_FILE_NAME.equals(path.toString()))
.findAny();
if (configFilePath.isPresent()) {
return;
}
}
}
fail("Configuration file update could not be detected");
}
/**
* Ensures that a modified or deleted cached files does not stay in the cache
*/
private void processFolderEvents(final WatchService watchService) {
WatchKey key = watchService.poll();
if (key != null) {
for (WatchEvent<?> e : key.pollEvents()) {
if (e.kind() == OVERFLOW) {
continue;
}
// Context for directory entry event is the file name of entry
@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) e;
Path path = ev.context();
logger.debug("Refreshing transformation file '{}'", path);
for (String fileEntry : cachedFiles.keySet()) {
if (fileEntry.endsWith(path.toString())) {
cachedFiles.remove(fileEntry);
}
}
}
key.reset();
}
}
/**
* 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;
}
}
/**
* 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;
}
}
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();
}
}
/**
* 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;
}
}
/**
* 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;
}
}
public void start() throws IOException {
if (existsAndReadyCheck()) {
return;
}
WatchService watcher = FileSystems.getDefault().newWatchService();
Path pathToWatch = FileSystems.getDefault().getPath(fileToWatch.getParent());
register(watcher, pathToWatch);
try {
LOG.info(String.format("Migration File Watcher: Watching: %s", fileToWatch.toString()));
startWatching(watcher);
} catch (InterruptedException ex) {
LOG.error("Migration File Watcher: Interrupted!");
} finally {
watcher.close();
}
}
@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;
}
}
}
/**
* 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;
}
}
private void createWatchService() {
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
WatchKey trustedKey = trustedDir.toPath().register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY
);
Thread thread = new Thread(new Watcher(watchService, trustedKey));
thread.setName("ua-certificate-directory-watcher");
thread.setDaemon(true);
thread.start();
} catch (IOException e) {
logger.error("Error creating WatchService.", e);
}
}
private synchronized WatchService getWatchService() throws TransformationException {
WatchService watchService = this.watchService;
if (watchService != null) {
return watchService;
}
try {
watchService = this.watchService = FileSystems.getDefault().newWatchService();
} catch (IOException e) {
logger.error("Unable to start transformation directory monitoring");
throw new TransformationException("Cannot get a new watch service.");
}
watchSubDirectory("", watchService);
return watchService;
}
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();
}
@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);
}
public void watch() throws InterruptedException, IOException {
try {
final Path directoryPath = file.toPath().getParent();
final WatchService watchService = FileSystems.getDefault().newWatchService();
directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
final WatchKey wk = watchService.take();
for (WatchEvent<?> event : wk.pollEvents()) {
final Path fileChangedPath = (Path) event.context();
if (fileChangedPath.endsWith(file.getName())) {
onModified();
}
}
wk.reset();
}
} catch (Exception e) {
logger.error("exception when handling change of mock file: {}", e.getMessage());
}
}
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();
}
}
/** {@inheritDoc} */
@Override
public WatchKey register( WatchService watcher, Kind<?>[] events, Modifier... modifiers ) throws IOException {
if ( watcher == null ) {
throw new NullPointerException();
}
if ( !(watcher instanceof UnixSshFileSystemWatchService) ) {
throw new ProviderMismatchException();
}
if ( !getFileSystem().provider().readAttributes( this, BasicFileAttributes.class ).isDirectory() ) {
throw new NotDirectoryException( this.toString() );
}
getFileSystem().provider().checkAccess( this, AccessMode.READ );
return ((UnixSshFileSystemWatchService) watcher).register( this, events, modifiers );
}
public void run() {
log.info("Running configuration updater..");
String configFilePath = CellStsUtils.getConfigFilePath();
Path directoryPath = Paths.get(configFilePath.substring(0, configFilePath.lastIndexOf("/")));
try {
while (true) {
WatchService watcher = directoryPath.getFileSystem().newWatchService();
directoryPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
log.debug("Waiting for config file change");
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
log.debug("Received events: ....");
for (WatchEvent event : events) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
log.info("Updating file on {} event", StandardWatchEventKinds.ENTRY_CREATE);
CellStsUtils.buildCellStsConfiguration();
CellStsUtils.readUnsecuredContexts();
}
if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
log.info("Updating file on {} event", StandardWatchEventKinds.ENTRY_MODIFY);
CellStsUtils.buildCellStsConfiguration();
CellStsUtils.readUnsecuredContexts();
}
}
}
} catch (IOException | InterruptedException | CelleryCellSTSException e) {
log.error("Error while updating configurations on file change ", e);
}
}
protected void watcherPid(final File pidFile) throws IOException {
final WatchService watcher = FileSystems.getDefault().newWatchService();
final Path path = Paths.get(".");
path.register(watcher, StandardWatchEventKinds.ENTRY_DELETE);
Executors.newFixedThreadPool(1, (runnable) -> {
final Thread tomcat = new Thread(runnable);
tomcat.setName("Tomcat PID Watcher: " + System.currentTimeMillis());
return tomcat;
}).execute(() -> {
try {
for (;;) {
final WatchKey watchKey = watcher.take();
final List<WatchEvent<?>> events = watchKey.pollEvents();
for (WatchEvent<?> event : events) {
final String fileName = ((Path) event.context()).toFile().getAbsolutePath();
if (pidFile.getAbsolutePath().equals(fileName)) {
LOGGER.info("tomcat.pid已被删除,应用进入退出流程");
System.exit(0);
}
}
watchKey.reset();
}
} catch (final InterruptedException e) {
LOGGER.info("Stoped File Watcher");
}
});
}
@Test
@Ignore
public void newWatchService() throws IOException {
Path pathToTest = Paths.get(clusterUri);
WatchService ws = pathToTest.getFileSystem().newWatchService();
Assert.assertNotNull(ws);
}
private void awaitLatchFile(final WatchService watchService) throws InterruptedException {
while (true) {
WatchKey watchKey = watchService.take();
if (isReleasedOrReleasable()) {
break;
}
watchKey.reset();
}
}
private static void openAndCloseWatcher(Path dir) {
FileSystem fs = FileSystems.getDefault();
for (int i = 0; i < ITERATIONS_COUNT; i++) {
try (WatchService watcher = fs.newWatchService()) {
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
} catch (IOException ioe) {
// ignore
}
}
}
private void watchSubDirectory(String subDirectory, final WatchService watchService) {
if (watchedDirectories.indexOf(subDirectory) == -1) {
String watchedDirectory = getSourcePath() + subDirectory;
Path transformFilePath = Paths.get(watchedDirectory);
try {
transformFilePath.register(watchService, ENTRY_DELETE, ENTRY_MODIFY);
logger.debug("Watching directory {}", transformFilePath);
watchedDirectories.add(subDirectory);
} catch (IOException e) {
logger.warn("Unable to watch transformation directory : {}", watchedDirectory);
cachedFiles.clear();
}
}
}
@Test
public void testPollingConfig() {
WatchServiceConfiguration polling = WatchServiceConfiguration.polling(50, MILLISECONDS);
WatchService watchService = polling.newWatchService(fs.getDefaultView(), fs.getPathService());
assertThat(watchService).isInstanceOf(PollingWatchService.class);
PollingWatchService pollingWatchService = (PollingWatchService) watchService;
assertThat(pollingWatchService.interval).isEqualTo(50);
assertThat(pollingWatchService.timeUnit).isEqualTo(MILLISECONDS);
}
private static WatchService createWatchService(final Path parentDir) {
try {
return parentDir.getFileSystem().newWatchService();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void watch() {
final WatchService watcher;
if (watchDir == null) {
return;
}
try {
watcher = FileSystems.getDefault().newWatchService();
watchDir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
logger.trace("Watching driver directory [{}]", watchDir);
} catch (IOException ex) {
logger.error("Could not register watcher for driver directory [{}]", watchDir);
return;
}
executor.submit(new Runnable() {
@Override
public void run() {
while (true) {
WatchKey key = null;
try {
key = watcher.take();
} catch (InterruptedException e) {
logger.error("Interrupted Exception encountered [{}]", e);
}
if (key != null) {
if (key.pollEvents().size() > 0) {
// Something has changed. That's all we need to know.
for (DriverWatcherListener listener : listeners) {
listener.onChange();
}
}
boolean isValid = key.reset();
if (!isValid) {
logger.error("Unable to watch driver directory. Watcher key invalid.");
}
}
}
}
});
}
private static void openAndCloseWatcher(Path dir) {
FileSystem fs = FileSystems.getDefault();
for (int i = 0; i < ITERATIONS_COUNT; i++) {
try (WatchService watcher = fs.newWatchService()) {
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
} catch (IOException ioe) {
// ignore
}
}
}
public LogSearchConfigLocalUpdater(final Path path, final WatchService watchService,
final InputConfigMonitor inputConfigMonitor, final Map<String, String> inputFileContentsMap,
final JsonParser parser, final JsonArray globalConfigNode, final Pattern serviceNamePattern) {
this.path = path;
this.watchService = watchService;
this.inputConfigMonitor = inputConfigMonitor;
this.inputFileContentsMap = inputFileContentsMap;
this.parser = parser;
this.globalConfigNode = globalConfigNode;
this.serviceNamePattern = serviceNamePattern;
}
private void process () throws IOException
{
logger.warn ( "Start watching: {}", this.path );
try ( final WatchService watcher = this.path.getFileSystem ().newWatchService () )
{
this.path.register ( watcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE );
processExisting ( this.path );
for ( ;; )
{
WatchKey key;
try
{
key = watcher.take ();
}
catch ( final InterruptedException e )
{
return;
}
for ( final WatchEvent<?> event : key.pollEvents () )
{
logger.debug ( "Handle event: {} - {}", event.kind (), event.context () );
handleEvent ( event );
}
if ( !key.reset () )
{
throw new RuntimeException ( "Key got cancelled" );
}
}
}
}