I am generating a log file and what i want is that i want to read the data periodically without having to read from the beginning each time. can anyone help.
public Boolean lineContains(final String messageToMatch) { File file = new File(path);
try {
Scanner scanner = new Scanner(file);
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum ;
if(line.contains(messageToMatch)) {
logger.info("LINE NUMBER " lineNum "MATCHED");
}}}
CodePudding user response:
I am generating a log file and what i want is that i want to read the data periodically without having to read from the beginning each time
I assume you mean you want to carry on reading from where you left off before.
If you keep the file open, then obviously the next place to read is just after the previous place you have read.
If you want to close the file (in the reader) then use the RandomAccessFile class, remember your position (getFilePointer), and seek to that position when you re-open the file.
In this case, you'll need to take precautions that it's "the same file" that you read previously. With log files, it's typical to close one log and open the next. To detect that, maybe check the create time, make sure the size doesn't decrease, etc. (I don't know if you can get the inode number via Java).
For a simpler solution, if you don't actually mind reading from the beginning and just want to be able to process new data, then remember the line number that you read up to before, and skip over that many lines the next time you open the file.
You'll still want to take precautions to make sure it's the same log file.
CodePudding user response:
here , the first match of the message is printed. so, same line number is always returned for similar message in log file