Watch Service erkennt Datei Änderung nicht

Otz

Bekanntes Mitglied
Hallo zusammen,

ich habe eine Text-Datei, in die von einem log4j SimpleSocketServer in unterschiedlichen Abständen verschiedene Nachrichten eingetragen werden.

Für diese Text-Datei habe ich ein Watcher Service implementiert, der mich über Änderungen informieren soll.
Leider funktioniert dies nur dann, wenn ich die Text-Datei anwähle oder aktualisiere.

Hier mal mein Quellcode:

Code:
...
Thread t2 = new Thread(new WatcherThread());
t2.start();
...

Code:
public class WatcherThread implements Runnable {

	@Override
	public void run() { 
WatchService watcher;
			
		try {
			watcher = FileSystems.getDefault().newWatchService();
			Path dir = Paths.get("log");
			dir.register(watcher, 
					StandardWatchEventKinds.ENTRY_CREATE,
					StandardWatchEventKinds.ENTRY_DELETE, 
					StandardWatchEventKinds.ENTRY_MODIFY );
			
			/*
	        ENTRY_CREATE: indicates that a directory or file is created.
	        ENTRY_DELETE: indicates that a directory or file is deleted.
	        ENTRY_MODIFY: indicates that a directory or file is modified.
	        OVERFLOW: indicates that the event might have been lost or discarded. 
	        This event is always implicitly registered so we don’t need to explicitly specify it in the register() method.
			*/
			
		
		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 == StandardWatchEventKinds.OVERFLOW) {
		            continue;
		        } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
		 
		            // process create event
		        	System.out.println("process create event");
		 
		        } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
		 
		            // process delete event
		        	System.out.println("process delete event");
		 
		        } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
		        	System.out.println("process modify event");
		        }
		    }
		 
		    // 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();
		}
	}
}
 
Zuletzt bearbeitet:

Neue Themen


Zurück
Oben