gpt4 book ai didi

java - java中的子目录和主目录监控

转载 作者:行者123 更新时间:2023-12-01 09:04:43 24 4
gpt4 key购买 nike

我的程序正在监视指定文件路径中的任何文件更改,如果有任何新文件到来,它会发出通知,但当父文件夹中创建任何子文件夹时会失败。父文件夹的文件路径正在被监视C:/play但是当创建了一个新的子文件夹时,如 C:/play/abc在父文件夹中,我的程序能够检测到,但是当我尝试将任何文件插入 abc 文件夹时,我的程序无法检测到已创建的新文件。我测试过various methods但不幸的是我不能让它工作。任何人都可以为我提供有关我的引用链接的任何指南吗?我的示例代码遵循我的引用链接中的指南

这是我添加检查子目录功能后的源代码

public class fileStatus 
{
public static void main(String [] args) throws InterruptedException
{
try(WatchService svc = FileSystems.getDefault().newWatchService())
{
Map<WatchKey, Path> keyMap = new HashMap<>();
Path path = Paths.get("C:/play");
fileStatus fd = new fileStatus();
fd.registerAll(path);
keyMap.put(path.register(svc,
StandardWatchEventKinds.ENTRY_CREATE),
path);
WatchKey wk ;
do
{
wk = svc.take();
Path dir = keyMap.get(wk);
for(WatchEvent<?> event : wk.pollEvents())
{
WatchEvent.Kind<?> type = event.kind();
Path fileName = (Path)event.context();
System.out.println("\nThe new file :"+fileName+ "Event :" +type); //print the new file name
}
}while(wk.reset());
}
catch(IOException e)
{
System.out.println("Problem io in somewhere");
}

}

private void registerAll(Path path) throws IOException
{
Files.walkFileTree(path, new SimpleFileVisitor<Path>()
{
@SuppressWarnings("unused")
public FileVisitResult preVisitDireotry(Path path,BasicFileAttributes attrs) throws IOException
{
return FileVisitResult.CONTINUE;
}
});

}
}



This是我的引用代码,我的文件夹结构如下所示,

/root
/Folder A
/test.txt
/Folder B
/abc.txt

最佳答案

简而言之,您只注册了要观看的父目录。您创建的任何子目录都不会被监视。请参阅here .

关于java - java中的子目录和主目录监控,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41376517/

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