是否有简单的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()方法获取目录的新快照,也许在两次迭代之间会有短暂的延迟-=但这似乎笨拙的。文件可能会达到几十兆字节。不必等待一个完整的“快照”文件被完全处理后再开始另一个文件的“快照”。

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

谢谢!

解决方法

使用2个目录。

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...