首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Tailer和WatchService

使用Tailer和WatchService
EN

Stack Overflow用户
提问于 2015-07-23 00:26:10
回答 1查看 233关注 0票数 1

通过使用下面的代码,我同时使用了Tailer和WatchService:

代码语言:javascript
复制
AgentTailerListener listener = new AgentTailerListener();
Tailer tailer;

WatchService watcher = FileSystems.getDefault().newWatchService();
while (true) {
    WatchKey watchKey;
    watchKey = Paths.get("/tmp").register(watcher, ENTRY_CREATE);
    watchKey = watcher.take();

    for (WatchEvent<?> event : watchKey.pollEvents()) {
        if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
            tailSource = event.context().toString();
            System.out.println(tailSource);
            File file = new File("/tmp/" + tailSource);
            String end = "log";

            if (file.getName().endsWith(end)) {
                tailer = TailerFactory.createTailer(file, listener);
                (new Thread(tailer)).start();
            }

        }
    }

    watchKey.reset();
    transport.close();
}

但问题是:我只想用尾部检查一个文件(就像停止线程,但我不能停止特定于文件的线程),并且当我通过echo命令写入文件时,并不是我写的所有字母都会出现。

当我连续几次使用echo编写相同的文本时,所有的字母都会被写入。

我看过这个主题,How to tail -f the latest log file with a given pattern,但我不知道我是否可以用它来解决我的问题(我不知道尾巴和尾巴之间的区别)。

EN

回答 1

Stack Overflow用户

发布于 2015-07-23 23:39:22

最后,我认为这样做效果更好:

代码语言:javascript
复制
AgentTailerListener listener = new AgentTailerListener();
Tailer tailer;
String tailSource;
Thread thread;

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

WatchKey watchKey;
watchKey = Paths.get("/tmp").register(watcher, ENTRY_CREATE);

List<Thread> threadList = new ArrayList<Thread>();
while (true) {
    watchKey = watcher.take();
    for (WatchEvent<?> event : watchKey.pollEvents()) {
    if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {

        tailSource = event.context().toString();
        System.out.println(tailSource);
        File file = new File("/tmp/" + tailSource);
        String end = "log";
        if (file.getName().endsWith(end)) {
            tailer= TailerFactory.createTailer(file, listener);
            if(threadList.isEmpty()){}
            else{
                Thread.sleep(1000);
                threadList.get(0).stop();
                threadList.clear();}
            System.out.println(threadList.size());
            threadList.add(thread = new Thread(tailer));
            threadList.get(0).start();
            }
    }
}
watchKey.reset();

} 

但是它创建了很多线程,我想我必须使用一个修复线程池。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31568820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档