一个简单的WatchService文件资源监控

分享一个简单的文件资源监控

package ch12;

/**
 * 监听watch需要手动停止
 */
import java.io.File;
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.WatchKey;
import java.nio.file.WatchService;

/**
 * 
 * @author admin 下午1:28:40
 */
public class FileWatch {
	public static void main(String[] args) {
		watch();
	}

	/**
	 * @author admin
	 */
	public static void watch() {
		/* 监控目标路径 */
		Path path = Paths.get("C:\\Users\\admin\\Desktop");
		try {
			/* 创建文件监控对象 */
			WatchService watchService = FileSystems.getDefault().newWatchService();
			/* 注册文件监控的所有事件类型 */
			path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
					StandardWatchEventKinds.ENTRY_MODIFY);
			/* 循环监测文件 */
			File root = new File(path.toUri());
			while (true) {
				WatchKey watchKey = watchService.take();
				/* 迭代触发事件的所有文件 */
				for (WatchEvent<?> event : watchKey.pollEvents()) {
					System.out.println(event.context().toString() + " 事件类型:" + event.kind());
					long free = root.getFreeSpace();
					long total = root.getTotalSpace();
					long usable = root.getUsableSpace();
					System.out.println("C盘总容量(单位:M):" + (total / 1024 / 1024));
					System.out.println("C盘总已用空间(单位:M):" + ((total - usable) / 1024 / 1024));
					System.out.println("C盘总可用空间(单位:M):" + (free / 1024 / 1024));
				}
				if (!watchKey.reset()) {
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,Java项目中可以使用WatchService实现动态修改配置文件即时生效的功能。WatchService是Java 7引入的文件监控机制,可以监控文件或目录的变化,例如创建、修改、删除等操作,并在发生变化时通知应用程序。通过使用WatchService,我们可以实时监控配置文件的变化,并在发生修改时重新加载配置文件,从而实现配置即时生效的功能。具体实现方式可以参考以下代码: ```java import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.HashMap; import java.util.Map; public class ConfigWatcher { private WatchService watchService; private Map<WatchKey, Path> keyPathMap; public ConfigWatcher(String path) throws Exception { watchService = FileSystems.getDefault().newWatchService(); keyPathMap = new HashMap<>(); Path dir = Paths.get(path); registerAll(dir); } private void registerAll(final Path start) throws IOException { Files.walkFileTree(start, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { WatchKey key = dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); keyPathMap.put(key, dir); return FileVisitResult.CONTINUE; } }); } public void watch() { while (true) { WatchKey key; try { key = watchService.take(); } catch (InterruptedException e) { return; } Path dir = keyPathMap.get(key); if (dir == null) { continue; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } WatchEvent<Path> ev = (WatchEvent<Path>) event; Path filename = ev.context(); Path child = dir.resolve(filename); if (kind == StandardWatchEventKinds.ENTRY_CREATE || kind == StandardWatchEventKinds.ENTRY_MODIFY) { // 重新加载配置文件 } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) { // 删除配置文件 } } boolean valid = key.reset(); if (!valid) { keyPathMap.remove(key); if (keyPathMap.isEmpty()) { break; } } } } } ``` 在上述代码中,我们通过watchService监控配置文件所在目录的变化,当有文件创建、修改、删除等操作时,会触发WatchEvent事件。我们可以在事件处理函数中重新加载配置文件,实现配置的即时生效。同时,我们也可以在事件处理函数中删除配置文件,防止无用的配置文件占用系统资源
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值