java - Java Watch Service 无法监视层次结构中定义为 UNC 路径的超过 50-60 个文件夹
问题描述
我一直在尝试通过 UNC 观看文件夹。主文件夹中有很多文件夹。当我运行监视服务时,它正在使用监视服务注册所有文件夹。注册所有这些文件夹后,监视服务会收到带有无效密钥的事件,即 key.isValid() 返回 false。此时特定文件夹被排除在手表之外。我已经重置了密钥,但它也给了我错误。简而言之,我无法查看那些从密钥中排除的文件夹。我什至尝试重新注册文件夹,但这又会生成无效密钥并且无法观看。我在同一台机器上用普通文件夹试过这个。他们工作正常。如果我遗漏了什么,请帮助我。如果我将文件夹限制在 50-60 左右,则手表服务不会收到任何无效的键事件,并且一切正常。
这是将创建文件夹数量的代码。
import java.io.File;
public class CreateDir {
public static void main(String args[]){
for(int j=0; j<1000; j++){
String folderName = "Folder"+j;
new File("\\\\Server2\\Shared Folder\\test\\" + folderName + "\\" + folderName + "_Folder1" + "\\" + folderName + "_Folder2" + "\\"
+ folderName + "_Folder3" + "\\" + folderName + "_Folder4" + "\\" + folderName + "_Folder5"+"\\"
+ folderName + "_Folder6" + "\\" + folderName + "_Folder7" + "\\" + folderName + "_Folder8" + "\\"
+ folderName + "_Folder9" + "\\" + folderName + "_Folder10").mkdirs();
}
}
}
这门课实际上正在观看这些 UNC 路径并提供有关事件的信息。
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;
private int total = 0;
@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, PrintWriter writer) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
if (trace) {
Path prev = keys.get(key);
if (prev == null) {
writer.println("register:"+dir);
} else {
if (!dir.equals(prev)) {
writer.println("update.........");
}
}
}
keys.put(key, dir);
}
/**
* Register the given directory, and all its sub-directories, with the
* WatchService.
*/
private void registerAll(final Path start, PrintWriter writer){
// register directory and sub-directories
try{
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
{
writer.println(++total+"Registering Path...."+dir.toUri());
try{
register(dir,writer);
}catch(IOException ex){
writer.println("Error occurred for Path..."+dir.getFileName());
}catch(Exception ex){
System.out.println("error");
}
return FileVisitResult.CONTINUE;
}
});
}catch(Exception ex){
writer.println("Not Registered ....."+ex.getMessage());
}
}
/**
* Creates a WatchService and registers the given directory
*/
WatchDir(Path dir, boolean recursive, PrintWriter writer) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<WatchKey,Path>();
this.recursive = recursive;
if (recursive) {
System.out.println("Starting Registering Path");
writer.println("Scanning %s ...\n"+ dir);
registerAll(dir, writer);
writer.println("Done.");
System.out.println("Done");
writer.println("Total Folders in Watch "+ total);
System.out.println("Total Folders in Watch "+ total);
} else {
register(dir,writer);
}
// enable trace after initial registration
this.trace = true;
}
/**
* Process all events for keys queued to the watcher
* @throws UnsupportedEncodingException
* @throws FileNotFoundException
*/
void processEvents() throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer1 = new PrintWriter("C:\\test\\key.txt");
for (;;) {
// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
writer1.println("Folder is "+key.watchable()+" And Key is "+ key.isValid());
System.out.println("Folder is "+key.watchable()+" And Key is "+ key.isValid());
} catch (InterruptedException x) {
writer1.println("Interupped Exception.........");
return;
}
Path dir = keys.get(key);
if (dir == null) {
writer1.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) {
writer1.println("Overflow event is caught.");
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);
writer1.println("Event Kind is "+event.kind().name() +" And Name is "+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, writer1);
}
} catch (Exception 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;
}
}
}
}
static void usage() {
System.err.println("usage: java WatchDir [-r] dir");
System.exit(-1);
}
public static void main(String[] args) throws IOException {
// register directory and process its events
PrintWriter writer = new PrintWriter("C:\\test\\watch.txt");
Path dir = Paths.get("\\\\Server1\\Shared Folder\\test");
new WatchDir(dir, true,writer).processEvents();
}
}
我已经用 JDK8 和 JDK 11 试过这个,两者都给出了同样的问题。
解决方案
推荐阅读
- python-3.x - 删除附加到数据框中值的垃圾('[',']','等)
- javascript - 如何使用以下代码将 function() 中的数组返回到 wordpress ajax.php 上的 javascript:
- django - “发送非空 'Sec-WebSocket-Protocol' 标头但未收到响应” Django 频道
- javascript - 如何使用javascript从链接打开模式框打印PDF文件?
- webpack - 防止在 webpack 中修改(最小化和优化)文件
- javascript - Reactive Forms 选择的选项是 formcontrol 中的 Object 对象
- authentication - 使用具有基于承载令牌的用户身份验证的应用程序对 IAP 安全测试环境进行 TestCafe 身份验证
- javascript - 如何在添加到购物车时更改 woocommerce 中的 javascript?
- winapi - 在 IFileOperationProgressSink::PreCopyItem 方法中跳过文件的 HRESULT 值
- sql - 联合所有:按合并排序(无子查询)