我使用此代码同时使用Tailer和WatchService:
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();
}
但问题是:我想只检查一个带有tailer的文件(比如停止线程,但是我无法阻止特定于文件的线程),当我通过echo命令写入文件时,并非我写的所有信件都出现了。
当我连续几次用echo写相同的文字时,所有的字母都被写出来。
我看到了这个主题,How to tail -f the latest log file with a given pattern,但我不知道我是否可以将它用于我的问题(我不知道尾巴和尾标之间的区别)。
答案 0 :(得分:0)
最后,我认为这更好:
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();
}
但它创建了很多线程,我想我必须使用修复线程池。