I use Tailer and WatchService at the same time by using this code:
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();
}
But the problem is: I want to check only one file with the tailer (like stoping the thread, but I can't stop a thread specific to a file), and when I write in a file by the echo command, not all the letters I wrote appear.
When I write the same text with echo several times in a row all the letters are written.
I saw this topic, How to tail -f the latest log file with a given pattern , but I don't know if I can use it for my problem (I don't know the difference between tail and tailer).
Finally, I think this works better:
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();
}
But it creates very many threads, I think I have to use a fix thread pool.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.