java7 WatchServiceDemo 文件系統監控

    本身想搞點東西,發現一個java7的新特性蠻好用的,找了一個damo,貼出來但願能幫助到有須要的人。 java

package com.wanzi.core;

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.io.IOException;
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 JavaWatchServiceDemo {
	private Path path = null;
	private WatchService watchService = null;

	private void initialize() {
		path = Paths.get("D:\\test"); // get the directory which needs
												// to be watched.
		try {
			watchService = FileSystems.getDefault().newWatchService();
			path.register(watchService, ENTRY_CREATE, ENTRY_DELETE,
					ENTRY_MODIFY); // register the watch service on the path.
									// ENTRY_CREATE-register file create event,
									// ENTRY_DELETE=register the delete event,
									// ENTRY_MODIFY- register the file modified
									// event
		} catch (IOException e) {
			System.out.println("IOException" + e.getMessage());
		}
	}

	/**
	 * Once it added to the watch list it will start to monitor the changes on
	 * the directory
	 */
	private void doMonitor() {
		WatchKey key = null;
		while (true) { // important - create an indefinite loop to watch the
						// file system changes.
			try {
				key = watchService.take();
				for (WatchEvent event : key.pollEvents()) {
					Kind kind = event.kind();
					System.out.println("Event on " + event.context().toString()
							+ " is " + kind);
				}
			} catch (InterruptedException e) {
				System.out.println("InterruptedException: " + e.getMessage());
			}
			boolean reset = key.reset();
			if (!reset)
				break;
		}
	}

	public static void main(String[] args) {
		JavaWatchServiceDemo watchservicedemo = new JavaWatchServiceDemo();
		watchservicedemo.initialize();
		watchservicedemo.doMonitor();
	}
}

    本地測試確實是能跑起來的~~ 在研究的語言的同時,應該把本身擅長的語言研究的更爲深刻纔是.. 加油! oop

相關文章
相關標籤/搜索