我正在尝试查看特定文件夹以进行更改,然后如果在其中发生任何添加/编辑/删除,我需要获取该文件夹及其子文件夹中所有文件的更改类型.我正在使用WatchService它,但它只观看单个路径,它不处理子文件夹.
这是我的方法:
try {
WatchService watchService = pathToWatch.getFileSystem().newWatchService();
pathToWatch.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
// loop forever to watch directory
while (true) {
WatchKey watchKey;
watchKey = watchService.take(); // This call is blocking until events are present
// Create the list of path files
ArrayList<String> filesLog = new ArrayList<String>();
if(pathToWatch.toFile().exists()) {
File fList[] = pathToWatch.toFile().listFiles();
for (int i = 0; i < fList.length; i++) {
filesLog.add(fList[i].getName());
}
}
// Poll for file system events on the WatchKey
for (final WatchEvent<?> …Run Code Online (Sandbox Code Playgroud) 我需要开发一个应用程序,一旦文件在预定义目录中创建,它将处理 csv 文件。预计会有大量传入文件。
我见过在生产中使用 Apache Commons IO 文件监控的应用程序。它工作得很好。我见过它一天处理多达 2100 万个文件。似乎 Apache Commons IO 文件监控会轮询目录并执行 listFiles 来处理文件。
我的问题:JDK WatchService 是否和 Apache Commons IO 文件监控一样好?有谁知道任何优点和缺点?