简体   繁体   English

Java:WatchService:File.Lastmodified返回0

[英]Java: WatchService : File.Lastmodified returns 0

I am trying to write a basic directory monitor that prints whether a file is created, changed, or deleted. 我正在尝试编写一个基本的目录监视器,以显示是否创建,更改或删除了文件。 But I am having trouble displaying the 'lastModified' time of each file. 但是我无法显示每个文件的“ lastModified”时间。 Please see full code below: 请在下面查看完整的代码:

public static void main(String[] args) throws IOException, InterruptedException {
    // TODO Auto-generated method stub

    WatchService watcher = FileSystems.getDefault().newWatchService();

    Path dir = Paths.get("C:\\Users\\User1\\Desktop\\test");

    WatchKey key = dir.register(watcher,

            StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY
            );

    for (;;) {


        WatchKey key2 = watcher.take(); 

        for ( WatchEvent<?> event : key.pollEvents()  ) {

            WatchEvent.Kind<?> kind = event.kind();


            WatchEvent<Path> ev = (WatchEvent<Path>) event; 

            Path filename = ev.context(); 
            File fullFilename = filename.toFile();

            System.out.println("Event: |"+kind+"| Filename: "+fullFilename.getName()+"|Time: "+fullFilename.lastModified());


            if (fullFilename.exists()) {


                System.out.println(fullFilename.getName()+" - Exists");

            }

            else {

                System.out.println("fullFileName does not exist");

            }

        }


        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }


}

The lastModified method returns 0. I have tried testing whether fileFullname object actually exists, and for some reason it doesn't. lastModified方法返回0。我尝试测试fileFullname对象是否确实存在,并且由于某种原因不存在。 Yet, when you use fileFullname.getName() it returns the filename just fine. 但是,当您使用fileFullname.getName()它返回的文件名就很好。

What am I doing wrong? 我究竟做错了什么?

I appreciate your help, and thank you in advance! 感谢您的帮助,并在此先感谢您!

You need resolve the filename against the watched directory. 您需要根据监视目录解析文件名。

You can not get the lastModified value because the context filesystem of the event does not have your watched directory as defaultDirectory , the defaultDirectory is the directory from the app runs, if you check the existence of fullFilename you will get false 您无法获取lastModified值,因为该事件的上下文文件系统没有您监视的目录为defaultDirectorydefaultDirectory是应用程序运行的目录,如果您检查fullFilename的存在,则将获得false

Path filename = ev.context(); 
File fullFilename = filename.toFile();
//fullFilename.exists(); returns false

so you need resolve it by this way 所以你需要这样解决

Path name = (Path) event.context();
//dir is you watched directory
File filename = dir.resolve(name).toFile();

The complete code 完整的代码

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class Snippet {
    public static void main(String[] args) throws IOException, InterruptedException {

        Path pathToWatch = FileSystems.getDefault().getPath("C:\\tmp\\test");
        try (WatchService watchService = pathToWatch.getFileSystem().newWatchService()) {
            Path dir = Paths.get("C:\\tmp\\test");
            dir.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
            WatchKey key = watchService.take();
            do {
                for (final WatchEvent<?> event : key.pollEvents()) {
                    Path name = (Path) event.context();
                    File filename = dir.resolve(name).toFile();
                    System.out.println(dir + ": " + event.kind() + ": " + event.context() + ", Modified: " + filename.lastModified());
                }
            } while (key.reset());
        }
    }
}

More information at docs.oracle.com (Watching a Directory for Changes) 有关更多信息,请访问docs.oracle.com(监视目录中的更改)

I hope this helps you. 我希望这可以帮助你。

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

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