【问题标题】:Watching a Directory and sub directory for create, modify and Changes in java观察目录和子目录以在 java 中创建、修改和更改
【发布时间】:2013-07-25 06:49:26
【问题描述】:

我已经在目录 C:/java/newfolder 中制作了一些用于检测更改的代码,它运行良好。我在下面给出。

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

public class DirectoryWatchExample {
public static void testForDirectoryChange(Path myDir){

        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 (Exception e) {
            System.out.println("Error: " + e.toString());
        }
}

public static void main (String[] args) {
    Path myDir = Paths.get("c:/java/newfolder/");
    //define a folder root
    testForDirectoryChange(myDir);

}
} 

现在我只看目录。但我只需要查看所有子目录。

例如:c:/java/newfolder/folder1, c:/java/newfolder/folder2, c:/java/newfolder/folder3......etc

我在子目录上面给出了例子

c:/java/newfolder/*..

我需要查看所有子目录给我一些解决方案吗?

【问题讨论】:

    标签: java


    【解决方案1】:

    您要做的是递归注册WatchService,并在后续的ENTRY_CREATE 事件中继续注册它。 Oracle 在此处提供了一个完整的示例:http://docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java

    通常我不会发布带有单个链接的帖子,但是我怀疑 Oracle 会删除一个相当基本的教程,而且答案过于冗长。以防万一,通过搜索“java watchservice recursive”很容易找到示例。

    【讨论】:

    • 我很怀疑,但它确实有效。给它一个输入目录名称,它也会监视所有子目录。这正是我想要的。感谢您发布链接。
    • 我也是。它在检测到他的创建时注册新文件夹。如果某些情况(服务器负载,小文件),我认为它可能会错过在子文件夹中创建的文件。
    • 很抱歉发布了 necroposting,但它的行为就像 Nereis 暗示的那样。 Oracle 示例的行为不是确定性的。尝试让它监视一个空目录,然后在其中复制一个中等大小的目录树。有些文件不会引起注意。
    【解决方案2】:

    这是我带来的..

        final WatchService watcher = FileSystems.getDefault().newWatchService();
    
        final SimpleFileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException
            {
                dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    
                return FileVisitResult.CONTINUE;
            }
        };
    
        Files.walkFileTree(Paths.get("/directory/to/monitor"), fileVisitor);
    

    【讨论】:

      【解决方案3】:

      我对@9​​87654321@ API 不熟悉,因此请对以下内容持保留态度。

      您正在注册一个用于监控的目录,并且每当其直接后代之一被修改/创建/删除时都会收到通知。

      您需要做的第一件事是注册其所有子目录以供观看:

      // Used to filter out non-directory files.
      // This might need to filter '.' and '..' out, not sure whether they're returned.
      public class DirectoryFilter implements FileFilter {
          public boolean accept(File file) {
              return file.isDirectory();
          }
      }
      
      
      // Add this at the end of your testForDirectoryChange method
      for(File dir: myDir.toFile().listFiles(new DirectoryFilter())) {
          testForDirectoryChange(dir.toPath());
      }
      

      这将递归地探索您的文件结构并注册每个目录以供观看。 请注意,如果您的目录树太深,递归可能不是一个可接受的解决方案,您可能需要“迭代”它。

      您需要做的第二件事是,每当您收到目录创建事件时,不要忘记注册新目录以进行监控。

      无论如何我都会这样做,但手头没有有效的 Java 1.7 安装,我无法对其进行测试。让我知道它是否有效!

      【讨论】:

        【解决方案4】:

        那么您想要列出目录中的文件/子目录吗? 您可以使用:

        File dir = new File("c:/java/newfolder/");
        File[] files = dir.listFiles();
        

        listFiles() 为您提供目录中的文件或 null 它不是目录。

        那么你可以这样做:

        for (File file: files){
             if (file.listFiles != null){
                  //It's a subdirectory
                  File [] subdirFiles = file.listfiles;
             }
        }
        

        【讨论】:

        • hai Luis 不会列出文件。我需要查看子目录。给我一些解决方案..
        • 子目录也在文件数组中。检查我的编辑。
        猜你喜欢
        • 2011-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-17
        • 2023-03-26
        相关资源
        最近更新 更多