Datei Beobachten: Wie gehe ich am besten vor?

Hallo Zusammen,

ich möchte ein Logfile-Reader schreiben. Die Datei (Logfile) soll beobachtet werden und bei jede Änderung sollen die neusten Zeilen angezeigt werden.

Auf anhieb fällt mir nur der folgende Ansatz ein:

Eine Endlosschleife mit Sleep Funktion, der alle paar Sekunden die letzte Veränderung (last modified) ausliest.
Ich habe momentan keine Idee, woran ich die neusten Zeilen erkennen kann, ohne die Datei jedesmal von anfang an auszulesen ?! Ich müsste mir die letzte Zeile merken, die Datei komplett durchlaufen, bis die neue Zeile nochmal kommt und anschließend die neusten Zeilen ausgeben.

Abgesehen davon würde ich gerne wissen, ob es eine bessere Möglichkeit gibt, als mit Hilfe der Endlisschleife eine Datei zu beobachten?

Am liebsten würde ich gerne die Datei in ein Stream werfen, damit die Veränderung automatisch angezeigt wird. Gibt es eine solche Möglichkeit?

Gruß
Angelika
 
Öhm wenn es sich um ein log4j Logging System handelt gehts am einfachstem mit nem SocketAppender. Solche Systeme gibt es auch schon fertig die das tun.
 
Öhm wenn es sich um ein log4j Logging System handelt gehts am einfachstem mit nem SocketAppender. Solche Systeme gibt es auch schon fertig die das tun.

Hallo Zeja,

meine Frage hat nichts mit log4j zutun.

Ich möchte eine Swing Anwendung schreiben. Mit der Anwendung kann man Logfiles auswählen. Diese sollen dann beobachtet werden. Bei Änderung möchte ich die neuste Information anzeigen.
Sowas gibt es wie Sand am Meer. Ich möchte aber eine eigene schreiben.

Gruß
Angelika
 
Hallo,

schau mal hier:
Java:
package de.tutorials;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class FileSystemWatcher {
	Map<String, FileInfo> snapshot = new ConcurrentHashMap<String, FileInfo>();
	volatile boolean stop;
	volatile List<File> watchedResources = new CopyOnWriteArrayList<File>();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new FileSystemWatcher().add("c:/temp/watch").start();

	}

	public FileSystemWatcher add(String resource) {
		File file = new File(resource);

		watchedResources.add(file);

		snapshot.putAll(snapshot(file));

		return this;
	}

	protected Map<String, FileInfo> snapshot(File file) {
		Map<String, FileInfo> map = new ConcurrentHashMap<String, FileInfo>();

		map.put(file.getAbsolutePath(), new FileInfo(file));

		//Recursive? 
		if (file.isDirectory()) {
			for (File item : file.listFiles()) {
				map.put(item.getAbsolutePath(), new FileInfo(item));
			}
		}

		return map;
	}

	public FileSystemWatcher start() {
		Executors.newSingleThreadExecutor().execute(createWatchThread());
		return this;
	}

	public void stop() {
		this.stop = true;
	}

	public Runnable createWatchThread() {
		return new Runnable() {
			public void run() {
				while (!stop) {
					for (File watchedResource : watchedResources) {
						Map<String, FileInfo> current = snapshot(watchedResource);
						checkForModifications(snapshot, current);
					}

					try {
						TimeUnit.SECONDS.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					// System.out.println(snapshot);
				}

				System.out.println("Stop watching resources: " + watchedResources);
			}
		};
	}

	public void checkForModifications(Map<String, FileInfo> snapshot, Map<String, FileInfo> current) {

		Set<String> newEntries = new HashSet<String>(current.keySet());
		newEntries.removeAll(snapshot.keySet());

		for (String newResource : newEntries) {
			System.out.println("New: " + newResource);
			snapshot.put(newResource, current.get(newResource));
		}

		for (Map.Entry<String, FileInfo> snapshotEntry : snapshot.entrySet()) {
			FileInfo snapshotFileInfo = snapshotEntry.getValue();
			FileInfo currentFileInfo = current.get(snapshotEntry.getKey());

			if (currentFileInfo == null) {
				System.out.println("deleted: " + snapshotEntry.getKey());
				snapshot.remove(snapshotEntry.getKey());
			} else {
				boolean modified = false;
				
				if (snapshotFileInfo.size != currentFileInfo.size) {
					System.out.println("modified (size): " + currentFileInfo);
					modified = true;
				} 

				//touch?
				if (snapshotFileInfo.lastModified != currentFileInfo.lastModified) {
					System.out.println("modified (time): " + currentFileInfo);
					modified = true;
				}

				if (modified) {
					snapshot.put(snapshotEntry.getKey(), currentFileInfo);
				}
			}
		}

	}
	
	static class FileInfo {
		String name;
		String location;
		long lastModified;
		long size;

		public FileInfo(File file) {
			this.name = file.getName();
			this.location = file.getParent();
			this.lastModified = file.lastModified();
			this.size = file.length();
		}

		@Override
		public String toString() {
			return "FileInfo [name=" + name + ", location=" + location + ", size=" + size + ", lastModified=" + lastModified + "]";
		}
	}
}

... oder hier:
http://www.tutorials.de/forum/java/...erungen-ueberwachen-mit-dem-watchservice.html

Gruß Tom
 

Neue Beiträge

Zurück