gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:09:36 29 4
gpt4 key购买 nike

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

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

}
}
}

任何帮助都会很棒!

最佳答案

您应该修改这部分代码:

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

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

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

关于Java:如何打印找到的字符串的下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30690354/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com