in java,how to get file name in the thread
I have an ArrayList
call开发者_运维知识库ed fileList
. It contains a list of file names. Through the for loop, I am creating the thread for every file name and monitoring the file by using TailListener
Java API. Now I want to get the file name for each message present in the files.
fileListener= new fileListener();
for(int i=0;i<fileList.Size();i++)
{
monitorFile(filelist.get(i));
}
private void monitorFile(String logFile) {
File pcounter_log = new File(logFile);
Tailer = new Tailer(pcounter_log, fileListener, 5000);
ThreadPoolExec.scheduleAtFixedRate(Tailer, 5, 5, TimeUnit.SECONDS);
}
public class fileListener extends TailerListenerAdapter {
String s= "abc";
public void handle(String line) {
if(line.contains(s)){
System.out.println(line);
}
}
}
In the above code, how do I get the file name for the corresponding log messages?
One simple way would be to use separate listeners for each file:
Change your fileListener
class to something like this:
public class FileListener extends TailerListenerAdapter {
private final String fileName;
public FileListener(String fileName) {
this.fileName = fileName;
}
public void handle(String line) {
if(line.contains(s)){
System.out.println(fileName + ": " + line);
}
}
}
Then simply instantiate a new FileListener
for each file you monitor:
private void monitorFile(String logFile) {
File pcounter_log = new File(logFile);
Tailer = new Tailer(pcounter_log, new FileListener(logFile), 5000);
ThreadPoolExec.scheduleAtFixedRate(Tailer, 5, 5, TimeUnit.SECONDS);
}
精彩评论