java NIO文件系统监控

package chpter15.test.ao1;

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.text.SimpleDateFormat;
import java.util.Date;

public class WatchServiceTest {

	public static void main(String[] args) throws IOException, InterruptedException {
		WatchService watchService = FileSystems.getDefault().newWatchService();
		Paths.get("c:\\").register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.OVERFLOW);
		SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		while(true) {
			WatchKey key = watchService.take();
			for(WatchEvent<?> event:key.pollEvents()) {
				System.out.println(bartDateFormat.format(new Date())+"\t"+"c:\\"+event.context()+"\t"+event.kind()+"\t");
				Thread.sleep(1);
			}
			
			boolean valid = key.reset();
			if(!valid) {
				break;
			}
		}
	}

}

猜你喜欢

转载自blog.csdn.net/wangjunji34478/article/details/79358755