4 , , : (1), 6 (2), .
, , :
barebones, :
public static void MonitorFile(String filePath)
throws FileNotFoundException, IOException, InterruptedException
{
int newLineCount = 0;
final int INITIAL_LINE_LIMIT = 6;
final int POLLING_INTERVAL = 1000;
FileReader file = new FileReader(filePath);
BufferedReader fr = new BufferedReader(file);
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) {
lineBuffer.add(line);
if (++lineCount > INITIAL_LINE_LIMIT) lineBuffer.remove();
}
else {
System.out.printf("%d %s%n", ++lineCount, line);
newLineCount++;
}
}
else
{
if (initialising)
{
initialising = false;
lineCount = Math.max(0, lineCount - INITIAL_LINE_LIMIT);
while((line = lineBuffer.poll()) != null)
System.out.printf("%d %s%n", ++lineCount, line);
System.out.println("finished pre-loading file: now monitoring changes");
}
if (newLineCount > 2) break;
else Thread.sleep(POLLING_INTERVAL);
}
}
}
:
- ,
BufferedReader , , - , .
- , , .
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