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


    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


source


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


source


if(s.contains(keyword))
  System.out.println(br.readline());

      

0


source







All Articles