watchservice 在linux下的使用

程序代码如下:

import java.io.IOException;     
import java.nio.file.FileSystems;     
import java.nio.file.Path;     
import java.nio.file.Paths;     
import java.nio.file.WatchEvent;     
import java.nio.file.WatchKey;     
import java.nio.file.WatchService;     

import static java.nio.file.StandardWatchEventKinds.*;     
      
public class watchserviceTest {     
         
    private WatchService watcher;     
         
    public watchserviceTest(Path path)throws IOException{     
        watcher = FileSystems.getDefault().newWatchService();     
        path.register(watcher, ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY);     
    }     
         
    public void handleEvents() throws InterruptedException{     
        while(true){     
            WatchKey key = watcher.take();     
            for(WatchEvent event : key.pollEvents()){     
                WatchEvent.Kind kind = event.kind();     
                     
                if(kind == OVERFLOW){  
                    continue;     
                }     
                     
                WatchEvent e = (WatchEvent)event;     
                Path context = (Path)e.context();     
                String fileName = context.toString();
            
                String message = "";
                if(kind.name() == "ENTRY_CREATE")
                {
                	message = fileName + "-----> create";
                }else if(kind.name() == "ENTRY_DELETE" ){
                	message = fileName + "-----> delete";
                }else if(kind.name() == "ENTRY_MODIFY"){
                	message = fileName + "-----> modify";
                }
                if (fileName.endsWith("swp")||fileName.endsWith("swpx"))
				{
					continue;
				}else{
					System.out.println(message);
				}
            }     
            if(!key.reset()){     
                break;     
            }     
        }     
    }     
         
    public static void main(String args[]) throws IOException, InterruptedException{     
    	String watchDir = "/tmp";
		System.out.println("Begin watching DIR: /tmp ");
        new watchserviceTest(Paths.get(watchDir)).handleEvents();     
    }     
}   

在linux下执行命令如下:

javac watchserviceTest.java
java -cp .:/istar/WatchService/watchserviceTest watchserviceTest


你可能感兴趣的:(java,WatchService)