相关疑难解决方法(0)

Java:在复制内容之前,WatchService会得到通知

我试图将一个非常小的文件复制并粘贴到一个由监视服务观察的文件夹中.第一次工作很好,但在所有后续复制和粘贴操作,我得到一个异常,另一个进程已经处理该文件.通过实验,我发现在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)

java windows watchservice

7
推荐指数
1
解决办法
2146
查看次数

WatchService有时会触发ENTRY_MODIFY两次,有时一次

我在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)

java rhel watchservice nio2

6
推荐指数
1
解决办法
2502
查看次数

标签 统计

java ×2

watchservice ×2

nio2 ×1

rhel ×1

windows ×1