Java:如何打印找到的字符串

时间:2015-06-07 05:30:00

标签: java input

此代码有效,它会打印该行,但我希望它能打印下一行。

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

        }
    }
}

任何帮助都会很棒!

4 个答案:

答案 0 :(得分:2)

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

    }

答案 1 :(得分:2)

您应该修改代码的这一部分:

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

在这里打印包含关键字的行。由于您要打印下一行,请使用BufferedReaderif条件内再次读取下一行。因此,它会是这样的:

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

答案 2 :(得分:0)

要在找到keyword后打印该行,我会做一些简单的事情:

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

答案 3 :(得分:0)

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