Reputation: 437
I am using the java scanner class for scanning log file and search for exception then once I find the exception I want to print 20 lines before it and 20 lines after it. Is there an option to return 20 lines once I found my exception The code like this.
Scanner in = null;
try {
in = new Scanner(new FileReader(f));
while(in.hasNextLine() && !result) {
result = in.nextLine().indexOf(searchString) >= 0;
if (result)
{
//return 20 lines
}
}
}
Thanks in advance.
Upvotes: 0
Views: 2566
Reputation: 124
You can read the file to a List and use ListIterator.
List<String> logList = Files.readAllLines(Paths.get(filename));
ListIterator iter = logList.listIterator();
String result = "match string";
while(iter.hasNext() && !result);
int indexMatch = iter.previousIndex();
// Print previous 20 lines and next 20 lines
for(int i=-20;i<40;i++){
System.out.println(logList.get(indexMatch+i));
}
}
Upvotes: 0
Reputation: 3594
Buffer the lines as you read them. When you find the error, read the next 20 and buffer those also. Then return the buffer.
Upvotes: 4