已知一个txt , 要搜索关键字并打出所在行全部内容。
开始方式是
String fileName = "MagazineList.txt";
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String nextLine = br.readLine();
我不太懂概念,虽然麻烦你们编出所有过程有点强人所难,还麻烦大家指教。
最好可以使JUnits运行
那如果一个关键字不存在文本中,怎么编辑输出说明它不存在文本中。因为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");
}
}