java watch service

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

public class Watch {
	/*
	 * 디렉토리 감시
	 */
	final static Kind<Path> ENTRY_CREATE = StandardWatchEventKinds.ENTRY_CREATE;
	final static Kind<Path> ENTRY_DELETE = StandardWatchEventKinds.ENTRY_DELETE;
	final static Kind<Path> ENTRY_MODIFY = StandardWatchEventKinds.ENTRY_MODIFY;
	final static Kind<Object> OVERFLOW = StandardWatchEventKinds.OVERFLOW;
	public static void watchService(){
		try {
			WatchService watcher = FileSystems.getDefault().newWatchService();
			Path dir = Paths.get("E:/test/unzipTest");
			dir.register(watcher,ENTRY_CREATE, ENTRY_DELETE,ENTRY_MODIFY,OVERFLOW);
			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 == OVERFLOW) {
						continue;
					} else if (kind == ENTRY_CREATE) {

						// process create event
						System.out.println("Create...."+fileName.getFileName());

					} else if (kind == ENTRY_DELETE) {

						// process delete event
						System.out.println("Delete...."+fileName.getFileName());

					} else if (kind == ENTRY_MODIFY) {

						// process modify event
						System.out.println("Modify...."+fileName.getFileName());

					}
				}

				// 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();
		}
	}
	/*
	 * 실행
	 */
	public static void main(String[] args) throws IOException, InterruptedException {
		watchService();
	}
}

댓글 남기기