2016-12-29 82 views
0

我的程序正在监视指定文件路径中的任何文件更改,如果有新文件到来,它将引发通知,但在父文件夹中创建任何子文件夹时会失败。父文件夹的文件路径是监视器C:/play但是当在父文件夹内创建像C:/play/abc这样的新子文件夹时,我的程序能够检测到,但是当我试图将任何文件插入到abc文件夹时,我的程序无法运行检测到新文件已经创建。我已经测试various methods,但不幸的是我不能让它工作。任何人都可以为我提供任何指导我的参考链接?我的示例代码是在我的参考链接中的指南

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

java中的子目录和主目录监视

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 
+1

你应该在你的意图。 – AxelH

回答

1

总之,您只注册了要观看的父目录。您创建的任何子目录都不会被监视。见here

+0

我试图起诉walkFileTree,但它也无法正常工作,我不确定它是否以错误的方式使用它? – yumi

+0

从你的代码中,我不确定你想用'walkfileTree'来做什么,但是你必须手动向观察者注册子目录。我的理解是,创作时不会自动监视它们。 – Kerry

+0

让我再次编辑我的问题,以帮助您了解我在做什么 – yumi