分享一个简单的文件资源监控
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();
}
}
}