gpt4 book ai didi

java - 观察者在更改后停止

转载 作者:行者123 更新时间:2023-12-02 07:41:04 25 4
gpt4 key购买 nike

如何将下面的 Watcher 转换为持续运行?我希望它即使在检测到更改后也能继续监听文件。也许是一个线程?

import java.io.IOException;
import java.nio.file.*;
import java.util.List;

public class Listener {

public static void main(String[] args) {

Path myDir = Paths.get("C:/file_dir/listen_to_this");

try {
WatchService watcher = myDir.getFileSystem().newWatchService();
myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent event : events) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("Created: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("Delete: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
System.out.println("Modify: " + event.context().toString());
}
}
} catch (IOException | InterruptedException e) {
System.out.println("Error: " + e.toString());
}
}
}

最佳答案

不需要更多线程。您可以简单地将其放入 while 循环中:

public static void main(String[] args) throws Exception {
Path myDir = Paths.get("C:/file_dir/listen_to_this");

WatchService watcher = myDir.getFileSystem().newWatchService();
myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

while (true) {
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent event : events) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("Created: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("Delete: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
System.out.println("Modify: " + event.context().toString());
}
}
watchKey.reset();
}
}

关于java - 观察者在更改后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11581845/

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