0

How to generate an event when the paste option(while copying a file) is selected in some folder, in which that event should get the path of that folder where the paste option is being selected.

4

2 回答 2

2

此代码监视添加、删除或修改文件的目录:

Path testDirectory = Files.createTempDirectory( getClass().getName());
WatchService watcher = FileSystems.getDefault().newWatchService();
testDirectory.register( watcher,
    StandardWatchEventKinds.ENTRY_CREATE, 
    StandardWatchEventKinds.ENTRY_MODIFY, 
    StandardWatchEventKinds.ENTRY_DELETE );
for(;;) {
   WatchKey key = watcher.take();
   log( "key = watcher.take()" );
   if( key.isValid()) {
      log( "key.isValid()" );
      List< WatchEvent< ? >> lst = key.pollEvents();
      for( WatchEvent<?> e : lst ) {
         log( "WatchEvent polled: " + e.kind() + ": " + e.context());
         if( e.kind() == StandardWatchEventKinds.ENTRY_CREATE ) {
            Path path = (Path)e.context();
            File file = path.toFile();
            addFile( new File( testDirectory.toFile(), file.getPath()));
         }
         else if( e.kind() == StandardWatchEventKinds.ENTRY_DELETE ) {
            Path path = (Path)e.context();
            File file = path.toFile();
            removeFile( new File( testDirectory.toFile(), file.getPath()));
         }
      }
      key.reset();
   }
}

这段代码涉及的类有:

io 教程的这一部分展示了更多内容并解释了这个 API 的动机。

于 2013-04-08T18:29:31.207 回答
0

是所需的Java 教程。 java.nio.file包提供了一个文件更改通知 API,称为 Watch Service API。此 API 使您能够向监视服务注册一个(或多个目录)。注册时,您告诉服务您感兴趣的事件类型:文件创建、文件删除或文件修改

更多关于它的信息

于 2013-04-08T18:35:33.303 回答