2013년 10월 6일 일요일

[자바1.7,JAVA7]파일시스템의 변화감시,모니터링, 자바7, 자바NIO

[자바1.7,JAVA7]파일시스템의 변화감시,모니터링, 자바7, 자바NIO, java.nio
 
아래 예제는 자바7, JAVA1.7의 NIO를 이용하여 데몬처럼 떠있으면서 파일시스템의 파일의 변화 등을 감지할 수 있는 예제 입니다. 많은 활용 바랍니다.
by 오라클자바커뮤니티, 오엔제이실무프로그래밍교육센터
 
import java.io.*;
import java.nio.file.*;
public class FileChange
{
   public static void main(String args[]) throws IOException, InterruptedException
   {
      monitoringDir("c:\\java");  
   }
   
   static void monitoringDir(String dir) throws IOException, InterruptedException
   {
    
       WatchService myWatchService = FileSystems.getDefault().newWatchService(); 
       
       //모니터링을 원하는 디렉토리 Path를 얻는다.
       Path path = Paths.get(dir); // Get the directory to be monitored       
      
       
       //모니터링 서비스를 할 path에 의해 파일로케이션을 등록
       WatchKey watchKey = path.register(myWatchService, 
            StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_MODIFY,
            StandardWatchEventKinds.ENTRY_DELETE); // Register the directory
       
       //무한루프
       while(true)
       {
       //변화가 감지되는 경우 이벤트 종류와 파일명을 출력
          for (WatchEvent event : watchKey.pollEvents())
          {
             System.out.println(event.kind() + ": "+ event.context()); 
          }
         
          
           //* Resets this watch key.
           //* @return  {@code true} if the watch key is valid and has been reset 
           //*          {@code false} if the watch key could not be reset because it is
           //*          no longer {@link #isValid valid}, 디렉토리등이 삭제되는 경우           
          if (!watchKey.reset())
          {
             break; // 디렉토리등이 삭제되는 경우
          }
       }
   }
}

[결과 c:\java 폴더의 a.java를 b.java로 수정 후]
 
ENTRY_DELETE: a.java
ENTRY_CREATE: b.java
ENTRY_MODIFY: b.java

오라클자바커뮤니티에서 설립한 개발자교육6년차 오엔제이프로그래밍 실무교육센터(오라클SQL,튜닝,힌트,자바프레임워크,안드로이드,아이폰,닷넷 실무개발강의)  









댓글 없음:

댓글 쓰기