是否有简单的Java逻辑来处理同一目录中预先存在的文件和新创建的文件



在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((方法获取目录的新快照,迭代之间可能会有短暂的延迟——=但这似乎很笨拙。文件可能有几十兆字节的数量级。如果不需要等待一整周的时间,那就太好了;快照";在开始另一个"文件"之前要完全处理的文件的数量;快照";的文件。

使用数据库来跟踪已处理的文件似乎过于复杂。

谢谢!

使用两个目录。

首先将现有文件移到临时目录中,然后将其复制回。这些文件和创建的文件都将作为新文件触发手表。

如果您使用的是Linux,则可以对每个现有文件尝试touch(未经测试,但可能足以触发监视(。

最新更新