gpt4 book ai didi

如果重命名,Java WatchService 将停止监视文件夹 (OSX)

转载 作者:行者123 更新时间:2023-11-30 06:28:53 25 4
gpt4 key购买 nike

我正在尝试在 MacOS (High Sierra) 上设置 WatchService,它似乎工作正常,除非我重命名目录。作为示例,我将“test”重命名为“hello”,这就是我得到的结果:

ENTRY_CREATE: /Users/david/Desktop/watchme/hello
update: /Users/david/Desktop/watchme/test -> /Users/david/Desktop/watchme/hello
ENTRY_DELETE: /Users/david/Desktop/watchme/test

我希望看到:

register: /Users/david/Desktop/watchme/hello

但这并没有发生,所以当我修改“hello”内部的任何内容时,我得到的唯一响应是:

ENTRY_MODIFY: /Users/david/Desktop/watchme/hello

没有关于“hello”中的文件或文件夹的信息

我直接从 Oracle 复制了以下代码,但对属性进行了硬编码,以便我可以在 Idea 中运行它:

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.*;

/**
* Example to watch a directory (or tree) for changes to files.
*/

public class WatchDir {

private final WatchService watcher;
private final Map<WatchKey,Path> keys;
private final boolean recursive;
private boolean trace = false;

@SuppressWarnings("unchecked")
private 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 (prev == null) {
System.out.format("register: %s\n", dir);
} else {
if (!dir.equals(prev)) {
System.out.format("update: %s -> %s\n", prev, dir);
}
}
}
keys.put(key, dir);
}

/**
* Register the given directory, and all its sub-directories, with the
* WatchService.
*/
private void registerAll(final Path start) throws IOException {
// register directory and sub-directories
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException
{
register(dir);
return FileVisitResult.CONTINUE;
}
});
}

/**
* Creates a WatchService and registers the given directory
*/
private WatchDir(Path dir, boolean recursive) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<>();
this.recursive = recursive;

if (recursive) {
System.out.format("Scanning %s ...\n", dir);
registerAll(dir);
System.out.println("Done.");
} else {
register(dir);
}

// enable trace after initial registration
this.trace = true;
}

/**
* Process all events for keys queued to the watcher
*/
private void processEvents() {
for (;;) {

// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}

Path dir = keys.get(key);
if (dir == null) {
System.err.println("WatchKey not recognized!!");
continue;
}

for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind kind = event.kind();

// TBD - provide example of how OVERFLOW event is handled
if (kind == OVERFLOW) {
continue;
}

// Context for directory entry event is the file name of entry
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);

// print out event
System.out.format("%s: %s\n", event.kind().name(), child);

if(child.toString().contains("testdir")) {
System.out.println("This is an update");
}

// if directory is created, and watching recursively, then
// register it and its sub-directories
if (recursive && (kind == ENTRY_CREATE)) {
try {
if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
registerAll(child);
}
} catch (IOException x) {
// ignore to keep sample readbale
}
}
}

// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
keys.remove(key);

// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}

private static void usage() {
System.err.println("usage: java WatchDir [-r] dir");
System.exit(-1);
}

@SuppressWarnings("ParameterCanBeLocal")
public static void main(String[] args) throws IOException {
// parse arguments
args = new String[2]; // Added for debug
args[0] = "-r"; // Added for debug
args[1] = "/Users/david/Desktop/watchme"; // Added for debug
if (args.length == 0 || args.length > 2)
usage();
boolean recursive = false;
int dirArg = 0;
if (args[0].equals("-r")) {
if (args.length < 2)
usage();
recursive = true;
dirArg++;
}

// register directory and process its events
Path dir = Paths.get(args[dirArg]);
new WatchDir(dir, recursive).processEvents();
}
}

最佳答案

这是一个有趣的问题。我在自己的 Mac 上尝试过,得到了相同的结果。

当我们将test重命名为hello时,操作系统首先创建hello,然后删除test,两者都< em>watchme 和 test 将获取事件。 watchme 文件夹的 WatchKey 获取 ENTRY_CREATE 和 ENTRY_DELETE 事件。在这一步中,虽然新的目录名称是hello,但是在这段代码之后

WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

我们得到的 key 仍然是test的watch key ,这就是我们在控制台中看到更新日志的原因。

ENTRY_CREATE: /Users/david/Desktop/watchme/hello
update: /Users/david/Desktop/watchme/test -> /Users/david/Desktop/watchme/hello
ENTRY_DELETE: /Users/david/Desktop/watchme/test

test 的 WatchKey 也收到了一个事件。但这个事件是一个无效事件,键(事实上这是hello现在的watchKey)将从键映射中删除。因此 hello 文件夹的更改将不会在控制台中显示任何内容。

这是有趣的事情。为什么当输入目录是hello时我们得到test的watchKey。当我调试代码时,将其停止在

WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

有一段时间,当收到hello的ENTRY_CREATE事件时,我得到hello的 key 而不是test的 key 并注册日志不更新日志。调用dir.register方法时,我们似乎无法立即看到hello文件夹。我不太清楚操作系统在重命名文件夹时会做什么,希望其他人回复。

这是我在processEvents中添加日志的测试代码,你可以自己尝试一下。

private void processEvents() {
for (; ; ) {
// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
Path dir = keys.get(key);
if (dir == null) {
System.err.println("WatchKey not recognized!!");
continue;
} else {
System.out.println("CurrentDir=" + dir.getFileName() + " keySize=" + keys.size() + " valid=" + key.isValid());
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
// TBD - provide example of how OVERFLOW event is handled
if (kind == OVERFLOW) {
continue;
}
// Context for directory entry event is the file name of entry
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
// print out event
System.out.format("%s: %s\n", event.kind().name(), child);
// if directory is created, and watching recursively, then
// register it and its sub-directories
if (recursive && (kind == ENTRY_CREATE)) {
try {
if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
registerAll(child);
}
} catch (IOException x) {
// ignore to keep sample readbale
}
}
}
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
System.out.println("Remove From keys");
keys.remove(key);
// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}

关于如果重命名,Java WatchService 将停止监视文件夹 (OSX),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46536301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com