Ronald DERAMUS
Ronald DERAMUS

Reputation: 93

Java: How to print the next line of found string

This code works and it prints the 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!

Upvotes: 3

Views: 2100

Answers (4)

Anindya Dutta
Anindya Dutta

Reputation: 1982

You should modify this part of your code:

while ((s=br.readLine())!=null) {
  if(s.contains(keyword))
      System.out.println(s);
}

Here you're printing the line that contains the keyword. Since you want to print the next line, use the BufferedReader to read the next line again inside the if condition. Therefore, 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);
    }
}

Upvotes: 2

Kip Diskin
Kip Diskin

Reputation: 192

    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;
        }

    }

Upvotes: 2

Kip Diskin
Kip Diskin

Reputation: 192

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

Upvotes: 0

1337joe
1337joe

Reputation: 2367

To print the line after keyword is found I'd do something simple like this:

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;
    }
}

Upvotes: 0

Related Questions