简体   繁体   English

监视目录和子目录以在Java中创建,修改和更改

[英]Watching a Directory and sub directory for create, modify and Changes in java

I have make some code for detect changed in directory C:/java/newfolder it working good. 我在目录C:/ java / newfolder中做了一些检测更改的代码,它工作正常。 i have given below. 我在下面给出。

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);

}
} 

now i watching only the directory. 现在我只看目录。 But i need to watch only the all sub directory. 但是我只需要看所有子目录。

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

i given examples above sub directory 我在子目录上方给出了示例

c:/java/newfolder/*.. c:/ java / newfolder / * ..

i need to watch the all sub directory give me some solutions ? 我需要观看所有子目录给我一些解决方案吗?

What you want to do is register the WatchService recursively and continue to register it upon subsequent ENTRY_CREATE events. 您要做的是递归注册WatchService并在随后的ENTRY_CREATE事件时继续注册它。 A complete example is provided by Oracle here: http://docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java Oracle在此处提供了一个完整的示例: http : //docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java

Normally I wouldn't place a post with a single link, however I doubt Oracle will be taking down a fairly basic tutorial and the answer is far too verbose. 通常,我不会在单个链接中发布帖子,但是我怀疑Oracle是否会删除一个相当基本的教程,答案太冗长了。 Just in case though, examples are easily found by searching for "java watchservice recursive". 为了以防万一,可以通过搜索“ java watchservice recursive”轻松找到示例。

Here is what I came with.. 这是我来的。

    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);

I'm not familiar with the Path API, so take the following with a grain of salt. 我对Path API并不熟悉,因此请注意以下几点。

You're registering one directory for monitoring, and will receive notifications whenever one of its direct descendants is modified / created / deleted. 您正在注册一个要监视的目录,每当其直接后代之一被修改/创建/删除时,它将接收通知。

The first thing you need to do is register all of its subdirectories for watching: 您需要做的第一件事是注册其所有子目录以进行观察:

// 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());
}

This will recursively explore your file structure and register every directory for watching. 这将递归地探索您的文件结构并注册每个目录以供观看。 Note that if your directory tree is too deep, recursion might not be an acceptable solution and you might need to 'iterify' it. 请注意,如果您的目录树太深,则递归可能不是可接受的解决方案,您可能需要对其进行“迭代”。

The second thing you need to do is, whenever you receive a directory creation event, not forget to register the new directory for monitoring. 您需要做的第二件事是,每当您收到目录创建事件时,请不要忘记注册新目录以进行监视。

That's how I'd do it anyway, but not having a valid Java 1.7 installation at hand, I can't test it. 无论如何,这就是我要这样做的方式,但是手头没有有效的Java 1.7安装,因此我无法对其进行测试。 Do let me know if it works! 让我知道它是否有效!

So what you want is listing the files/subdirectories within a directory? 那么,您想要列出目录中的文件/子目录吗? You can use: 您可以使用:

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

listFiles() gives you the Files in a directory or null it it's not a directory. listFiles()为您提供目录中的文件,如果不是目录,则为null。

Then you can do: 然后,您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM