返回首页


今天,我开始尝试一些新功能,我们在Java 7。首先是该文件的系统WatchService让我们听没有汇集到一个目录中的变化。看起来真的很棒。你刚才注册将有关更改的通知,并等待得到您的通知。它的最好的部分是,你可以指定你想尽可能多的听众,从不同的线程,即使没有代码的变化,它是所有线程安全的。下面是我做了什么,以获取有关文件被修改/删除/添加到我的非常重要的TEMP目录的通知:

public class PathTest {



    private static void listenForChanges(File file) throws IOException {

        Path path = file.toPath();

        if (file.isDirectory()) {

            WatchService ws = path.getFileSystem().newWatchService();

            path.register(ws, StandardWatchEventKind.ENTRY_CREATE, 

              StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);

            WatchKey watch = null;

            while (true) {

                System.out.println("Watching directory: " + file.getPath());

                try {

                    watch = ws.take();

                } catch (InterruptedException ex) {

                    System.err.println("Interrupted");

                }

                List<WatchEvent<?>> events = watch.pollEvents();

                watch.reset();

                for (WatchEvent<?> event : events) {

                    Kind<Path> kind = (Kind<Path>) event.kind();

                    Path context = (Path) event.context();

                    if (kind.equals(StandardWatchEventKind.OVERFLOW)) {

                        System.out.println("OVERFLOW");

                    } else if (kind.equals(StandardWatchEventKind.ENTRY_CREATE)) {

                        System.out.println("Created: " + context.getFileName());

                    } else if (kind.equals(StandardWatchEventKind.ENTRY_DELETE)) {

                        System.out.println("Deleted: " + context.getFileName());

                    } else if (kind.equals(StandardWatchEventKind.ENTRY_MODIFY)) {

                        System.out.println("Modified: " + context.getFileName());

                    }

                }

            }

        } else {

            System.err.println("Not a directory. Will exit.");

        }

    }



    public static void main(String[] args) {

        if (args.length > 0) {

            File file = new File(args[0]);

            try {

                System.out.println("Listening on: " + file);



                listenForChanges(file);

            } catch (IOException ex) {

                ex.printStackTrace();

            }

        } else {

            System.out.println("Pass directory path as parameter");

        }

    }

}

是一个棘手的事情,当使用WatchService。你要记住,重置后,你调查事件的WatchKey,否则将停止更新(只有第一个目录的变化将执行你的代码,其余部分将不会做任何事情)。

回答

评论会员:游客 时间:2012/02/04
kimptoc:嗨,我最近做了一些Ruby的Web服务客户端的东西,可以reccomend萨翁imgsrc=我觉得有点笨重,但绝对功能-理想情况下,我很乐意将自动生成客户端代理对象的问候,克里斯
bluesarita:嗨,
此代码不正确执行。有人可以帮助我
IM工作与NetBeans 7.0.1和2.1.1服务器Tomcat 7.0.1地铁
非常感谢
:8569117 |会员
评论会员:游客 时间:2012/02/04
抱歉。发布此代码使用后的一段时间。一些错误得到英寸我已经更新了,它已经在我的博客文章。请再次检查:{A}如果您有任何问题,请添加评论。问题再次抱歉