2012-07-20 89 views
0

如何將下面的觀察者轉換爲不斷運行?即使在檢測到更改後,我也希望它繼續監聽文件。一個線程也許?觀察者在變更後停止

import java.io.IOException; 
import java.nio.file.*; 
import java.util.List; 

public class Listener { 

    public static void main(String[] args) { 

     Path myDir = Paths.get("C:/file_dir/listen_to_this"); 

     try { 
      WatchService watcher = myDir.getFileSystem().newWatchService(); 
      myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); 
      WatchKey watckKey = watcher.take(); 
      List<WatchEvent<?>> events = watckKey.pollEvents(); 
      for (WatchEvent event : events) { 
       if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { 
        System.out.println("Created: " + event.context().toString()); 
       } 
       if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) { 
        System.out.println("Delete: " + event.context().toString()); 
       } 
       if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { 
        System.out.println("Modify: " + event.context().toString()); 
       } 
      } 
     } catch (IOException | InterruptedException e) { 
      System.out.println("Error: " + e.toString()); 
     } 
    } 
} 

回答

2

不需要任何更多的線程。你可以簡單地把它放在while循環內:

public static void main(String[] args) throws Exception { 
    Path myDir = Paths.get("C:/file_dir/listen_to_this"); 

    WatchService watcher = myDir.getFileSystem().newWatchService(); 
    myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); 

    while (true) { 
     WatchKey watckKey = watcher.take(); 
     List<WatchEvent<?>> events = watckKey.pollEvents(); 
     for (WatchEvent event : events) { 
      if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { 
       System.out.println("Created: " + event.context().toString()); 
      } 
      if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) { 
       System.out.println("Delete: " + event.context().toString()); 
      } 
      if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { 
       System.out.println("Modify: " + event.context().toString()); 
      } 
     } 
     watchKey.reset(); 
    } 
}