I have a log file which is constantly updated with new lines of data. I need to get new added data in java as soon as it's written. For now my solution is:
public static void readNonStop(String filename, boolean goToEnd, FileReadCallback readCallback) {
if(readCallback == null) {
return;
}
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
try {
String line = br.readLine();
int lineNumber = 0;
if(goToEnd) {
while(br.readLine() != null) {}
}
while (true) {
if(line != null) {
readCallback.onRead(lineNumber++, line);
} else {
Thread.sleep(1);
}
line = br.readLine();
}
} finally {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
But I have a feeling that there should be a better way. I don't like the idea of a constant running loop with a "sleep" inside and would prefer some sort of an event driven approach.
If I rely on FileSystem events to reopen the file each time it is modified, it introduces a delay.
What is the correct way of doing it for this situation?
Tailer
uses the same logic as my code, it reads in a loop with aThread.sleep
delay. But it feels good to confirm that I had the right idea, thanks! @Zeta, thank you! \$\endgroup\$WatcherService
introduces a delay up to 6 seconds in my tests, so unfortunately it is not an option. Looks like I will go with a looped read. \$\endgroup\$