Java: how to print next line of found line
This code works and it prints a line, but I would like it to print the next line.
import java.io.*;
public class SearchTextFile {
//
public static void main(String args[]) throws Exception {
int tokencount;
FileReader fr = new FileReader("c:\\searchtxt.txt");
BufferedReader br = new BufferedReader(fr);
String s;
int linecount = 0;
String keyword = "something";
String line;
while ((s = br.readLine()) != null) {
if (s.contains(keyword))
System.out.println(s);
}
}
}
Any help would be great!
+3
source to share
4 answers
You should change this part of your code:
while ((s=br.readLine())!=null) {
if(s.contains(keyword))
System.out.println(s);
}
Here you are printing a string containing a keyword. Since you want to print the next line, use BufferedReader
to read the next line again inside the condition if
. Hence, it would be something like this:
while ((s=br.readLine())!=null) {
if(s.contains(keyword)) {
//System.out.println(s);
String nextLine = br.readLine();
System.out.println(nextLine);
}
}
+2
source to share