我正在用Java语言编写一个cod4服务器控制器(我知道有非常好的服务器控制器,但我想从中学习)。现在我想根据日志文件中的条目采取特定的操作,该文件经常由cod更新,并且文件可能会变得非常大。现在,我如何有效地读取文件中每秒左右发生更改的部分?
或者,有没有办法将日志文件中更改的所有内容实时发送到Java?(我读到了一些关于管道的内容)。服务器在linux上运行。它不需要日志文件仍然保存在相同的位置,因为所有的东西都应该通过Java,我可以用它保存它。
大约1秒或2秒的延迟是可以接受的,但不能再长了。
发布于 2011-05-04 23:56:11
也许你可以执行一个'tail -f logfile.txt‘子进程并监控输出流?
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html
发布于 2011-05-05 00:09:23
在读取日志文件时,您可以在没有更多条目时暂停,并在以后继续处理。在写入文件时,该进程将继续运行,并且只会读取附加到末尾的其他行。
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
}
}注意:如果文件被关闭并滚动,这可能无法工作,您必须做一些更复杂的操作来处理它。
发布于 2011-05-05 00:14:55
您可以使用RandomAccessFile。你可以像这样存储指向最后一个红色字节的指针:
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是一种处理来自文件的新输入的方法。
这离卓越还很远,但我想你已经明白了。
https://stackoverflow.com/questions/5886202
复制相似问题