使用java监控一个目录下文件的变动

直接上代码:

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

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

public class MyFileWatcher {

	// 只能监控该目录下的文件/文件夹的变动(不监控子目录)
	static final String aPath = "E:/tmp";

	public static void main(String[] args) throws Throwable {

		System.out.println("Starting watcher for " + aPath);
		Path p = Paths.get(aPath);
		WatchService watcher = FileSystems.getDefault().newWatchService();
		Kind<?>[] watchKinds = { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY };
		p.register(watcher, watchKinds);

		boolean run = true;
		while (run) {
			WatchKey key = watcher.take();
			for (WatchEvent<?> e : key.pollEvents()) {
				//e.kind()是事件类型
				//e.context()是发生变动的文件/文件夹的名字
				System.out.println("Saw event " + e.kind() + " on " + e.context());
				if (e.context().toString().equals("stop.txt")) {
					System.out.println("stop monitoring");
					run = false;
					break;
				}
			}
			if (!key.reset()) {
				System.out.println("Key failed to reset");
			}
		}

	}

}

你可能感兴趣的:(java)