Java read a logfile live

こ雲淡風輕ζ 提交于 2019-12-06 04:57:45

Maybe you could execute a 'tail -f logfile.txt' subprocess and monitor the output stream?

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html

While you are reading the log file, you can pause when there are no more entries, and continue processing later. The process would continue running while the file is being written to and would only read additional lines appended to the end.

BufferedReader br = ...;
String line = null;
while (true) {
  line = br.readLine();
  if (line == null) // nothing more to read, wait... 
  {
    Thread.sleep(delay);
  } else {
    process(line); // take action
  }
}

Note: if the file is closed and rolled over, this probably won't work, and you'll have to do something more sophisticated to handle that.

You could use RandomAccessFile. You could store the pointer to the last byte you have red like this:

String pathToYourFile = "/path/to/your/logfile";
long lastBytePosition = 0;
boolean shouldStop = false;
while (! shouldStop) {
    Thread.sleep(2000);
    File f = new File(pathToYourFile);
    long length = f.length();
    RandomAccessFile raf = new RandomAccessFile(f, "r");
    byte[] buff = new byte[(int) (length - lastBytePosition)];
    raf.readFully(buff, (int) lastBytePosition, (int) (length - lastBytePosition));
    shouldStop = processChunk(buff);
    lastBytePosition = (int) length;
}

...where processChunk is a method to deal with new input from a file.

It's very far from excellence, but I think you got the idea.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!