我试图将一个非常小的文件复制并粘贴到一个由监视服务观察的文件夹中.第一次工作很好,但在所有后续复制和粘贴操作,我得到一个异常,另一个进程已经处理该文件.通过实验,我发现在Windows创建文件时通知我的服务,而不是在复制内容时通知我的服务.如果我锁定文件,Windows无法复制任何数据,文件为空.另一方面,如果我将文件移动到目录中,一切正常.
这是Windows的错误吗?我无法在mac或Linux工作站上测试它.或者也许只是我无能为力.任何帮助表示赞赏.
我的代码如下所示:
try (WatchService watchService = importPath.getFileSystem().newWatchService()) {
importPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
handleExistingFiles();
try {
do {
WatchKey watchKey = watchService.take();
if (!watchKey.isValid()) {
continue;
}
boolean hasCreationEvents = false;
for (WatchEvent<?> event : watchKey.pollEvents()) {
hasCreationEvents |= event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE);
}
watchKey.reset();
if (hasCreationEvents) {
handleNewFiles();
}
}
while (!Thread.currentThread().isInterrupted());
}
catch (InterruptedException ignoredEx) {
Thread.currentThread().interrupt();
}
}
Run Code Online (Sandbox Code Playgroud) 我在WatchServiceOracle中使用这个例子:
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.LinkOption.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;
public class WatchDir {
private final WatchService watcher;
private final Map<WatchKey,Path> keys;
private final boolean recursive;
private boolean trace = false;
@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>)event;
}
/**
* Register the given directory with the WatchService
*/
private void register(Path dir) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
if (trace) {
Path prev = keys.get(key);
if …Run Code Online (Sandbox Code Playgroud)