java 编程,搜索txt中关键字

已知一个txt , 要搜索关键字并打出所在行全部内容。
开始方式是
String fileName = "MagazineList.txt";
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String nextLine = br.readLine();
我不太懂概念,虽然麻烦你们编出所有过程有点强人所难,还麻烦大家指教。
最好可以使JUnits运行

import java.io.*;
public class Keyword{
public void test(String keyword)throws IOException{
String fileName = "MagazineList.txt";
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String nextLine;

int line=1;
while((nextLine=br.readLine())!=null){
if(nextLine.indexOf(keyword)>-1){
System.out.println(line+"行 "+nextLine);
}
line++;
}
}

public static void main(String[] args)throws IOException{
new Keyword().test("java");
}
}

一个完整的例子,请参考追问

那如果一个关键字不存在文本中,怎么编辑输出说明它不存在文本中。因为while 循环会一直循环,而如果没有这个关键字,那么只要输出一遍说明就行了。纠结了

追答

import java.io.*;
public class Keyword{
public void test(String keyword)throws IOException{
boolean bFound = false;
String fileName = "MagazineList.txt";
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String nextLine;

int line=1;
while((nextLine=br.readLine())!=null){
if(nextLine.indexOf(keyword)>-1){
System.out.println(line+"行 "+nextLine);
bFound=true;
}
line++;
}
if(!bFound){

System.out.println("Not found any in file.");

}

}

public static void main(String[] args)throws IOException{
new Keyword().test("java");
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-11
例如,你想找的关键字为String s = "Hello",那么你可以调用 nextLine.contains(s),看看这一行是不是包含"Hello",如果返回true则包含,false则不包含,当返回true时,System.out.println(nextLine);即可,加油!!我也才学不是很久
第2个回答  2013-09-11
用for循环 ,检测nextline中 是否包含相关的字符串,如果包含就打印出来
相似回答