I’m trying to implement a log tailer that will continue tailing after the previous file has been deleted and replaced by a new one (forever). So, I don’t have to run this program every time we restart the server (that prints out log).
This is my code.
public void tail(String file) throws InterruptedException, IOException {
waitUntilFileExist(file);
File f = new File(file);
BufferedReader br = new BufferedReader(new FileReader(file.trim()));
br.skip(f.length());
String line = null;
while (f.exists()) {
f = new File(file);
line = br.readLine();
if (line == null) {
Thread.sleep(1000);
} else {
if (msl != null) {
//Send line to attached interface
msl.onMessage(line);
}
}
}
waitUntilFileExist(file);
tail(file);
}
public void waitUntilFileExist(String file) throws InterruptedException {
File f = new File(file);
if (!f.exists()) {
System.out.println("File doesn't exists");
Thread.sleep(1000);
waitUntilFileExist(file);
} else {
System.out.println("File does exists");
}
}
First, it will check whether the specified file exists? and while it does exists, read the file and print the line. If the file is deleted while it’s reading, it will wait until the file is re-created and then call the tail method.
I test this out on a Linux box and it works fine but i’m not sure if this is the right way to do it.
Do you have any alternative way to do this?
Will this works for a production environment like days and months?
Your program will fail with stack overflow error because every time you go deeper and deeper with recursive method calls in both methods
tailandwaitUntilFileExist, and never get out from them.I make better variant of your code:
But this variant also not perfect! You may loose some lines because can be situation when something will be written to file between lines
waitUntilFileExist(file);andbr.skip(f.length());.If you need tail on unix system it is better to use tail console tool. You can start separate process from java and consume it’s output. This variant will guarantee 0% loses when file is deleted and created again.