java7 WatchServiceDemo 文件系统监控

旧城冷巷雨未停 提交于 2019-12-10 03:33:14

    自己想搞点东西,发现一个java7的新特性蛮好用的,找了一个damo,贴出来希望能帮助到有需要的人。

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();
	}
}

    本地测试确实是能跑起来的~~ 在研究的语言的同时,应该把自己擅长的语言研究的更为深入才是.. 加油!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!