问题描述
在Java中,这是处理特定目录中文件“快照”的几种方法之一:
String directory = "/path/to/directory";
List<File> fileList = Arrays.asList((new File(directory)).listFiles());
fileList.parallelStream.forEach(file->{
Path fileAsPath = file.toPath();
// Assume the process method finishes by deleting the file or moving it to another directory
process(fileAsPath);
});
WatchService watchService = FileSystems.getDefault().newWatchService();
Path directoryAsPath = Paths.get(directory);
WatchKey watchKey = directoryAsPath.register(watchService,ENTRY_CREATE);
while (true) {
WatchKey key;
key = watchService.take();
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
continue;
}
Path filename = event.context();
// Again,assume the process method finishes by deleting the file or moving it
// to another directory
process(filename);
}
}
处理目录中预先存在的文件(例如处理开始时)以及处理随后添加的文件,将是一种相当直接的方法吗?
我想一个简单的方法是将逻辑的第一块置于无限循环中-只是让listFiles()方法获取目录的新快照,也许在两次迭代之间会有短暂的延迟-=但这似乎笨拙的。文件可能会达到几十兆字节。不必等待一个完整的“快照”文件被完全处理后再开始另一个文件的“快照”。
谢谢!
解决方法
使用2个目录。
首先将现有文件移至临时目录,然后将其复制回。这些文件以及创建的文件都将作为新文件触发手表。
如果您使用的是Linux,则可以尝试touch
每个现有文件(未经测试,但足以触发手表)。