I'm trying to use Java to implement the Unix tail utility to read a log file as new lines are added. The log file has new lines written every 15 minutes. Once the BufferedReader reaches the end of the file, I have it sleep for a few minutes and when it wakes up it checks if new lines exist in the file. My code looks something like this:
String line;
BufferedReader br = new BufferedReader(new FileReader("logfile.log"));
while (alive) {
line = br.readline();
if (line != null) {
processLine(line);
} else {
Thread.sleep(1000 * 60 * 5);
}
}
For some reason after the BufferedReader reads the last line for the first time, it will not be able to detect any new lines that come in after that point. Does anyone have any ideas? Thanks!
* Update * The really weird thing is that this code works fine if I only read the log for the current day. However if I read the previous day, close it, and then open the current day, the problem exists. Using data from previous days log is a requirement of the program.
Test code looks like this:
String yestFile = "\\\\2012\\06\\28\\logfile.log";
String todayFile = "\\\\2012\\06\\29\\logfile.log";
FileWriter out;
String outputFile = "c:\\temp\\brOut.txt";
File outFile = new File(outputFile);
if (!outFile.exists()) {
outFile.createNewFile();
}
out = new FileWriter(outputFile);
String line;
String file = yestFile;
while (true) {
BufferedReader br = new BufferedReader(new FileReader(file));
while (true) {
line = br.readLine();
if (line != null) {
out.write(line + "\n");
} else {
if (file.equals(yestFile)) {
br.close();
br = null;
file = todayFile;
break;
}
Thread.sleep(1000 * 60);
}
}
}
* Update 2 * Thanks for all suggestions, but I decided the most effective solution is just to prevent from hitting the end of the file until the end of the day. Each line of the log indicates a time for when that event happened so I just use that to lag 20 minutes behind the current system time.
long diff = System.currentTimeMillis() - eventCal.getTimeInMillis();
if (diff < _20_MINUTES) {
Thread.sleep(_20_MINUTES - diff);
}