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
Ronald DERAMUS
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
Anindya Dutta
source
to share
boolean isFound = false;
String line = null;
while (line = br.readline() != null){
if(isFound){
System.out.print(line)
isFound = false;
}
if(line.contains(keyword)){
isFound = true;
}
}
+2
Kip diskin
source
to share
To print the line after keyword
, I would do something simple:
boolean foundString = false;
while ((s = br.readLine()) != null) {
if (s.contains(keyword)) {
System.out.println(s);
foundString = true;
} else if (foundString) {
System.out.println(s);
foundString = false;
}
}
0
1337joe
source
to share
if(s.contains(keyword))
System.out.println(br.readline());
0
Kip diskin
source
to share