虽然还有其他4个答案,我不认为任何地址都贵点:(1)打印最后6号线和(2) 然后继续监视文件并打印新行。
我也认为你应该保持它的简单,以更好地传达你的代码的意图,并删除错误的风险:
- 只使用一个
BufferedReader
而非RandomAccessFile
- 这就是BufferedReader
是
- ,而不是使用阵列只使用一个FIFO队列就像
ArrayDeque<String>
- 这是一个完美的使用情况,并在“ringbuffer”实现完全封装内ArrayDeque
准系统实现其做这一切会是这样的:
public static void MonitorFile(String filePath)
throws FileNotFoundException, IOException, InterruptedException
{
// Used for demo only: count lines after init to exit function after n new lines
int newLineCount = 0;
// constants
final int INITIAL_LINE_LIMIT = 6;
final int POLLING_INTERVAL = 1000;
// file readers
FileReader file = new FileReader(filePath);
BufferedReader fr = new BufferedReader(file);
// read-and-monitor loop
boolean initialising = true;
Queue<String> lineBuffer = new ArrayDeque<String>(INITIAL_LINE_LIMIT);
int lineCount = 0;
while (true) {
String line= fr.readLine();
if (line != null)
{
if (initialising) { // buffer
lineBuffer.add(line);
if (++lineCount > INITIAL_LINE_LIMIT) lineBuffer.remove();
}
else { // print
System.out.printf("%d %s%n", ++lineCount, line);
newLineCount++;
}
}
else
{
// No more lines, so dump buffer and/or start monitoring
if (initialising)
{
initialising = false;
// reset the line numbers for printing
lineCount = Math.max(0, lineCount - INITIAL_LINE_LIMIT);
// print out the buffered lines
while((line = lineBuffer.poll()) != null)
System.out.printf("%d %s%n", ++lineCount, line);
System.out.println("finished pre-loading file: now monitoring changes");
}
// Wait and try and read again.
if (newLineCount > 2) break; // demo only: terminate after 2 new lines
else Thread.sleep(POLLING_INTERVAL);
}
}
}
考虑的要点:
- 对于它的价值,我会通过
BufferedReader
作为一个参数所以这变得更加普遍,
- 这需要某种取消,所以它不会永远监视。
- 您可以使用file change monitoring,而不是轮询和睡眠您的线程,但该代码将比适合此答案更复杂。
上面的代码给出以下输出
2 test line b
3 test line c
4 test line d
5 test line e
6 test line f
7 test line g
finished pre-loading file: now monitoring changes
8 test line h
9 test line i
10 test line j
11 test line k
[爪哇IO执行的Unix/Linux“尾-f的](http://stackoverflow.com/questions/557844/java-io-implementation -of-unix-linux-tail -f) – Reimeus
我不确定为什么这已经被重复关闭,问题说明与链接问题不一样(它是读取文件然后监视新行),而是首先显示最近的6行(OP无法工作),然后继续监视。 –