下面列出了怎么用java.nio.file.WatchEvent.Kind的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) throws IOException {
FileListener listener = new FileListener() {
@Override
public void onEvent(String rootPath, WatchEvent<Path> event) {
Kind<Path> kind = event.kind();
String fileName = event.context().getFileName().toString();
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
System.err.println(rootPath +"/"+fileName +" "+ event.kind().name());
}
}
@Override
public Kind<?>[] events() {
return new Kind<?>[] { StandardWatchEventKinds.ENTRY_MODIFY };
}
};
ResourceListener.addListener("E:/jPersist2", listener);
ResourceListener.addListener("E:/MyDownloads/Download", listener);
}
@Override
public void handleFileChanged(Kind<?> operation, String fileAbsolutePathname) {
if (StandardWatchEventKinds.ENTRY_CREATE.equals(operation)) {
DecryptedFile recentlyRemovedEntry = recentlyRemoved.getIfPresent(fileAbsolutePathname);
if (recentlyRemovedEntry != null) {
addOrUpdate(recentlyRemovedEntry);
}
return;
}
if (StandardWatchEventKinds.ENTRY_DELETE.equals(operation)) {
remove(fileAbsolutePathname);
return;
}
// Other cases not supported -- not needed
}
private void registerWithSubDirectories(AbstractWatchService watchService, Path toWatch) throws IOException {
Files.walkFileTree(toWatch, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path subDir, BasicFileAttributes attrs)
throws IOException {
Kind<?>[] kinds = watchService.getWatchEventKinds(subDir);
if (kinds != null) {
registerDirectoryInternal(watchService, kinds, subDir);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
if (exc instanceof AccessDeniedException) {
logger.warn("Access to folder '{}' was denied, therefore skipping it.",
file.toAbsolutePath().toString());
}
return FileVisitResult.SKIP_SUBTREE;
}
});
}
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
File f = path.toFile();
if (!f.isHidden() && f.getName().endsWith(".cfg")) {
configDispatcher.processConfigFile(f);
}
} else if (kind == ENTRY_DELETE) {
// Detect if a service specific configuration file was removed. We want to
// notify the service in this case with an updated empty configuration.
File configFile = path.toFile();
if (configFile.isHidden() || configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) {
return;
}
configDispatcher.fileRemoved(configFile.getAbsolutePath());
}
}
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
File file = path.toFile();
if (!file.isHidden()) {
try {
URL fileUrl = file.toURI().toURL();
if (ENTRY_DELETE.equals(kind)) {
removeFile(fileUrl);
}
if (file.canRead() && (ENTRY_CREATE.equals(kind) || ENTRY_MODIFY.equals(kind))) {
importFile(fileUrl);
}
} catch (MalformedURLException e) {
logger.error("malformed", e);
}
}
}
private void fullEventAssertionsByKind(String fileName, Kind<?> kind, boolean osSpecific) throws Exception {
waitForAssert(() -> assertThat(watchService.allFullEvents.size() >= 1, is(true)), DFL_TIMEOUT * 2,
DFL_SLEEP_TIME);
if (osSpecific && ENTRY_DELETE.equals(kind)) {
// There is possibility that one more modify event is triggered on some OS
// so sleep a bit extra time
Thread.sleep(500);
cleanUpOsSpecificModifyEvent();
}
assertEventCount(1);
FullEvent fullEvent = watchService.allFullEvents.get(0);
assertThat(fullEvent.eventPath.toString(), is(WATCHED_DIRECTORY + File.separatorChar + fileName));
assertThat(fullEvent.eventKind, is(kind));
assertThat(fullEvent.watchEvent.count() >= 1, is(true));
assertThat(fullEvent.watchEvent.kind(), is(fullEvent.eventKind));
String fileNameOnly = fileName.contains(File.separatorChar + "")
? fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1, fileName.length())
: fileName;
assertThat(fullEvent.watchEvent.context().toString(), is(fileNameOnly));
// Clear all the asserted events
watchService.allFullEvents.clear();
}
private void processEvent(Path dir, WatchEvent<Path> event) {
// Context for directory entry event is the file name of entry
Path relChild = event.context();
Path child = dir.resolve(relChild);
Kind<Path> kind = event.kind();
if(kind == ENTRY_MODIFY) {
handleModification(child, externalInitiator);
} else if(kind == ENTRY_CREATE) {
handleCreation(child, externalInitiator);
} else if(kind == ENTRY_DELETE) {
model.delete(child, externalInitiator);
} else {
throw new AssertionError("unreachable code");
}
}
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
File f = path.toFile();
if (!f.isHidden() && f.getName().endsWith(".cfg")) {
configDispatcher.processConfigFile(f);
}
} else if (kind == ENTRY_DELETE) {
// Detect if a service specific configuration file was removed. We want to
// notify the service in this case with an updated empty configuration.
File configFile = path.toFile();
if (configFile.isHidden() || configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) {
return;
}
configDispatcher.fileRemoved(configFile.getAbsolutePath());
}
}
private void fullEventAssertionsByKind(String fileName, Kind<?> kind, boolean osSpecific) throws Exception {
waitForAssert(() -> assertThat(watchService.allFullEvents.size() >= 1, is(true)), DFL_TIMEOUT * 2,
DFL_SLEEP_TIME);
if (osSpecific && kind.equals(ENTRY_DELETE)) {
// There is possibility that one more modify event is triggered on some OS
// so sleep a bit extra time
Thread.sleep(500);
cleanUpOsSpecificModifyEvent();
}
assertEventCount(1);
FullEvent fullEvent = watchService.allFullEvents.get(0);
assertThat(fullEvent.eventPath.toString(), is(WATCHED_DIRECTORY + File.separatorChar + fileName));
assertThat(fullEvent.eventKind, is(kind));
assertThat(fullEvent.watchEvent.count() >= 1, is(true));
assertThat(fullEvent.watchEvent.kind(), is(fullEvent.eventKind));
String fileNameOnly = fileName.contains(File.separatorChar + "")
? fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1, fileName.length())
: fileName;
assertThat(fullEvent.watchEvent.context().toString(), is(fileNameOnly));
// Clear all the asserted events
watchService.allFullEvents.clear();
}
private void registerWithSubDirectories(AbstractWatchService watchService, Path toWatch) throws IOException {
Files.walkFileTree(toWatch, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path subDir, BasicFileAttributes attrs)
throws IOException {
Kind<?>[] kinds = watchService.getWatchEventKinds(subDir);
if (kinds != null) {
registerDirectoryInternal(watchService, kinds, subDir);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
if (exc instanceof AccessDeniedException) {
logger.warn("Access to folder '{}' was denied, therefore skipping it.",
file.toAbsolutePath().toString());
}
return FileVisitResult.SKIP_SUBTREE;
}
});
}
@SuppressWarnings("unchecked")
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
logger.debug("New watch event {} for path {}.", kind, path);
if (kind == OVERFLOW) {
return;
}
final WatchEvent<Path> ev = (WatchEvent<Path>) event;
final Path filename = ev.context();
logger.debug("Reloading javascript file {}.", filename);
manager.removeFromCache(filename.toString());
}
/**
* Precondition: Event and child must not be null.
* @param kind type of the event (create, modify, ...)
* @param source Identifies the related file.
*/
private void handleEvent(Kind<Path> kind, Path source) {
try {
if(PathUtils.isFileHidden(source)){
return;
}
if (kind.equals(ENTRY_CREATE)) {
addNotifyEvent(new NotifyFileCreated(source));
} else if (kind.equals(ENTRY_MODIFY)) {
addNotifyEvent(new NotifyFileModified(source));
} else if (kind.equals(ENTRY_DELETE)) {
addNotifyEvent(new NotifyFileDeleted(source));
} else if (kind.equals(OVERFLOW)) {
// error - overflow... should not happen here (continue if such an event occurs).
// handled already
logger.warn("Overflow event from watch service. Too many events?");
} else {
logger.warn("Unknown event received");
}
} catch (InterruptedException iex) {
// put into queue failed
logger.info("Handling event interrupted.", iex);
}
}
private void processKey(WatchKey key) throws IOException {
Path watchDir = (Path) key.watchable();
for (WatchEvent<?> event : key.pollEvents()) {
Kind<?> kind = event.kind();
if (kind.equals(StandardWatchEventKinds.OVERFLOW)) {
if (PROP_IGN_OVERFLOW)
continue; // Sometimes it's better to ignore than interrupt fair playing
throw new IOException("Overflow");
}
// Resolve paths and verify is not exclusion
Path path = watchDir.resolve((Path) event.context());
Deque<String> stringPath = toPath(dir.relativize(path));
if (matcher != null && !matcher.shouldVerify(stringPath))
continue; // Exclusion; should not be verified
// Verify is REALLY modified (not just attributes)
if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
HashedEntry entry = hdir.resolve(stringPath);
if (entry != null && (entry.getType() != HashedEntry.Type.FILE || ((HashedFile) entry).isSame(path, digest)))
continue; // Modified attributes, not need to worry :D
}
// Forbidden modification!
throw new SecurityException(String.format("Forbidden modification (%s, %d times): '%s'", kind, event.count(), path));
}
key.reset();
}
public AbstractWatchKey(
AbstractWatchService watcher,
Watchable watchable,
Iterable<? extends WatchEvent.Kind<?>> subscribedTypes,
int queueSize) {
this.watcher = requireNonNull(watcher);
this.watchable = watchable; // nullable for Watcher poison
this.events = new ArrayBlockingQueue<>(queueSize);
Set<Kind<?>> types = new HashSet<Kind<?>>();
subscribedTypes.forEach(types::add);
this.subscribedTypes = Collections.unmodifiableSet(types);
}
protected JWatchKey register(JPath path, Kind<?>[] events, Modifier ... modifiers)
{
JWatchKey key = new JWatchKey(this, path, events, modifiers);
synchronized (this) {
_watchList.add(key);
}
return key;
}
public JWatchKey(JWatchService watchService,
JPath path,
Kind<?>[] events,
Modifier ... modifiers)
{
Objects.requireNonNull(events);
_watchService = watchService;
_path = path;
_events = events;
_modifiers = modifiers;
_watchHandle = path.getBfsFile().watch(pathString -> onWatch(pathString));
}
@Override
public WatchKey register(WatchService watcher, Kind<?>[] events,
Modifier... modifiers) throws IOException
{
if (events.length == 0) {
throw new IllegalArgumentException(L.l("no events specified to watch on: {0}", toUri()));
}
JWatchService jWatcher = (JWatchService) watcher;
WatchKey key = jWatcher.register(this, events, modifiers);
return key;
}
/**
* Process watch events.
*
* @param key the key
* @param keys the keys
*/
private void processWatchEvents(WatchKey key, List<WatchEvent<?>> keys) {
for (WatchEvent<?> watchEvent : keys) {
Kind<?> watchEventKind = watchEvent.kind();
// Sometimes events are created faster than they are registered
// or the implementation may specify a maximum number of events
// and further events are discarded. In these cases an event of
// kind overflow is returned. We ignore this case for now
if (watchEventKind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
Path dir = (Path) key.watchable();
Path fullPath = dir.resolve((Path) watchEvent.context());
FileWatcherUpdateInterface parentObj = watcherMap.get(key);
if (parentObj != null) {
if (watchEventKind == StandardWatchEventKinds.ENTRY_CREATE) {
// A new file has been created
parentObj.fileAdded(fullPath);
} else if (watchEventKind == StandardWatchEventKinds.ENTRY_MODIFY) {
ReloadManager.getInstance().fileModified(fullPath);
// The file has been modified.
parentObj.fileModified(fullPath);
} else if (watchEventKind == StandardWatchEventKinds.ENTRY_DELETE) {
parentObj.fileDeleted(fullPath);
}
}
}
}
@SuppressWarnings("unchecked")
private static void processEvents(File watchedDir, Path file) {
for (;;) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event: key.pollEvents()) {
Kind<?> kind = event.kind();
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path name = ev.context();
Path child = watchedDir.toPath().resolve(name);
if (kind == ENTRY_DELETE && child.equals(file)) {
return;
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
}
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
File file = path.toFile();
if (!file.isHidden()) {
if (ENTRY_DELETE.equals(kind)) {
provider.removeResources(file);
} else if (file.canRead()) {
provider.importResources(file);
}
}
}
@Override
protected Kind<?>[] getWatchEventKinds(Path directory) {
if (directory != null && isNotEmpty(folderFileExtMap)) {
String folderName = directory.getFileName().toString();
if (folderFileExtMap.containsKey(folderName)) {
return new Kind<?>[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY };
}
}
return null;
}
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
File toCheck = getFileByFileExtMap(folderFileExtMap, path.getFileName().toString());
if (toCheck != null && !toCheck.isHidden()) {
checkFile(modelRepository, toCheck, kind);
}
}
@Override
public WatchKey register(WatchService watcher, Kind<?>[] events,
Modifier... modifiers) throws IOException {
if (watcher == null || events == null || modifiers == null) {
throw new NullPointerException();
}
// Not implemented now
// The Hadoop API for notification is not stable
throw new IOException("Not implemented");
}
@Override
public WatchKey register(
WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers)
throws IOException {
// TODO(buck_team): do not recourse to default Path implementation
return asDefault().register(watcher, events, modifiers);
}
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
File toCheck = getFileByFileExtMap(folderFileExtMap, path.getFileName().toString());
if (toCheck != null && !toCheck.isHidden()) {
checkFile(modelRepo, toCheck, kind);
}
}
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
File file = path.toFile();
if (!file.isHidden()) {
if (kind.equals(ENTRY_DELETE)) {
provider.removeResources(file);
} else if (file.canRead()) {
provider.importResources(file);
}
}
}
public UnixSshPathWatchKey( UnixSshFileSystemWatchService watchService, UnixSshPath dir, Kind<?>[] kinds, long pollingInterval, TimeUnit pollingIntervalTimeUnit ) {
this.watchService = watchService;
this.dir = dir;
this.kindsToWatch = new HashSet<>();
this.kindsToWatch.addAll( Arrays.asList( kinds ) );
this.pollingInterval = pollingInterval;
this.pollingIntervalTimeUnit = pollingIntervalTimeUnit;
this.cancelled = false;
this.initialized = false;
this.addMap = new HashMap<>();
this.deleteMap = new HashMap<>();
this.modifyMap = new HashMap<>();
this.state = State.READY;
}
public void watchVideoCaptureSystem(Path path) throws IOException, InterruptedException {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
System.out.println("Watching captures ...");
//start an infinite loop
while (true) {
//retrieve and remove the next watch key
final WatchKey key = watchService.poll(11, TimeUnit.SECONDS);
if (key == null) {
throw new IllegalStateException("The video capture system is jammed. Missed capture!");
}
//get list of events for the watch key
for (WatchEvent<?> watchEvent : key.pollEvents()) {
//get the kind of event (create, modify, delete)
final Kind<?> kind = watchEvent.kind();
//handle OVERFLOW event
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
//get the filename for the event
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
final Path filename = watchEventPath.context();
final Path child = path.resolve(filename);
if (Files.probeContentType(child).equals("image/jpeg")) {
//print it out the video capture time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
System.out.println("Video capture successfully at: " + dateFormat.format(new Date()));
} else {
Files.deleteIfExists(child);
throw new IllegalStateException("Unauthorized file type has been added!");
}
}
//reset the key
boolean valid = key.reset();
//exit loop if the key is not valid (if the directory was deleted, per example)
if (!valid) {
break;
}
}
}
}
}
public void watchTray(Path path) throws IOException, InterruptedException {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
System.out.println("Printer watcher ready ...");
//start an infinite loop
while (true) {
//retrieve and remove the next watch key
final WatchKey key = watchService.poll(10, TimeUnit.SECONDS);
//get list of events for the watch key
if (key != null) {
for (WatchEvent<?> watchEvent : key.pollEvents()) {
//get the filename for the event
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
final Path filename = watchEventPath.context();
//get the kind of event (create, modify, delete)
final Kind<?> kind = watchEvent.kind();
//handle OVERFLOW event
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("Sending the document to print -> " + filename);
Runnable task = new Printer(path.resolve(filename));
Thread worker = new Thread(task);
//we can set the name of the thread
worker.setName(path.resolve(filename).toString());
//store the thread and the path
threads.put(worker, path.resolve(filename));
//start the thread
worker.start();
}
if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println(filename + " was successfully printed!");
}
}
//reset the key
boolean valid = key.reset();
//exit loop if the key is not valid (if the directory was deleted, per example)
if (!valid) {
threads.clear();
break;
}
}
if (!threads.isEmpty()) {
for (Iterator<Map.Entry<Thread, Path>> it =
threads.entrySet().iterator(); it.hasNext();) {
Map.Entry<Thread, Path> entry = it.next();
if (entry.getKey().getState() == Thread.State.TERMINATED) {
Files.deleteIfExists(entry.getValue());
it.remove();
}
}
}
}
}
}
public void watchFolder(Path path) throws IOException, InterruptedException {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
System.out.println("Watching: " + path);
//start an infinite loop
while (true) {
//retrieve and remove the next watch key
final WatchKey key = watchService.take();
//get list of pending events for the watch key
for (WatchEvent<?> watchEvent : key.pollEvents()) {
//get the kind of event (create, modify, delete)
final Kind<?> kind = watchEvent.kind();
//handle OVERFLOW event
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
//get the filename for the event
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
final Path filename = watchEventPath.context();
//print it out
System.out.println(kind + " -> " + filename);
}
//reset the key
boolean valid = key.reset();
//exit loop if the key is not valid (if the directory was deleted, per example)
if (!valid) {
break;
}
}
}
}