[英]Is there simple Java logic for processing both pre-existing and newly created files in the same directory?
在 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
每個現有文件(未經測試,但可能足以觸發監視)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.