ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Watch Service 사용법 ( 1.7 버전 )
    카테고리 없음 2015. 6. 28. 21:59
    반응형



      To Do 자바 Watch Service

      특정 디렉토리를 감지 하고 있다가

      디렉토리에 이벤트 발생시 알려 준다.

       

      import java.io.IOException;

      import java.nio.file.FileSystems;

      import java.nio.file.Path;

      import java.nio.file.Paths;

      import java.nio.file.StandardWatchEventKinds;

      import java.nio.file.WatchEvent;

      import java.nio.file.WatchEvent.Kind;

      import java.nio.file.WatchKey;

      import java.nio.file.WatchService;

       

      public class WatchServiceTest {

      final static Kind<Path> ENTRY_CREATE =

      StandardWatchEventKinds.ENTRY_CREATE;

      final static Kind<Path> ENTRY_DELETE =

      StandardWatchEventKinds.ENTRY_DELETE;

      final static Kind<Path> ENTRY_MODIFY =

      StandardWatchEventKinds.ENTRY_MODIFY;

      final static Kind<Object> OVERFLOW     =

      StandardWatchEventKinds.OVERFLOW;

      public static void main(String[] args) {

      try {

      WatchService watcher = FileSystems.getDefault()

      .newWatchService();

      Path dir = Paths.get("감시할 폴더 경로");

      dir.register(watcher,ENTRY_CREATE,

      ENTRY_DELETE,ENTRY_MODIFY,OVERFLOW);

      while (true) {

          WatchKey key;

          try {

              // wait for a key to be available

              key = watcher.take();

          } catch (InterruptedException ex) {

              return;

          }

       

          for (WatchEvent<?> event : key.pollEvents()) {

              // get event type

              WatchEvent.Kind<?> kind = event.kind();

       

              // get file name

              @SuppressWarnings("unchecked")

              WatchEvent<Path> ev = (WatchEvent<Path>) event;

              Path fileName = ev.context();

             

              System.out.println(kind.name() + ": " + fileName+" 변경 감지..");

       

              if (kind == OVERFLOW) {

                  continue;

              } else if (kind == ENTRY_CREATE) {

       

                  // process create event

              System.out.println("Create...."+fileName.getFileName());

       

              } else if (kind == ENTRY_DELETE) {

       

                  // process delete event

              System.out.println("Delete...."+fileName.getFileName());

       

              } else if (kind == ENTRY_MODIFY) {

       

                  // process modify event

              System.out.println("Modify...."+fileName.getFileName());

       

              }

          }

       

          // IMPORTANT: The key must be reset after processed

          boolean valid = key.reset();

          if (!valid) {

              break;

          }

      }

      } catch (IOException e) {

      // TODO Auto-generated catch block

      e.printStackTrace();

      }

      }

      }

       


    반응형
Designed by Tistory.