我有我正努力寻找具有多行字符串的文本文件。一个单一的字符串,我能够搜索,但我需要多行被搜索的字符串。
我试图寻找这是工作的罚款单行。
public static void main(String[] args) throws IOException
{
File f1=new File("D:\\Test\\test.txt");
String[] words=null;
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String s;
String input="line one";
// here i want to search for multilines as single string like
// String input ="line one"+
// "line two";
int count=0;
while((s=br.readLine())!=null)
{
words=s.split("\n");
for (String word : words)
{
if (word.equals(input))
{
count++;
}
}
}
if(count!=0)
{
System.out.println("The given String "+input+ " is present for "+count+ " times ");
}
else
{
System.out.println("The given word is not present in the file");
}
fr.close();
}
以下是该文件的内容。
line one
line two
line three
line four
使用StringBuilder
的是,从文件中读取每一行,并将它们追加到StringBuilder
与lineSeparator
StringBuilder lineInFile = new StringBuilder();
while((s=br.readLine()) != null){
lineInFile.append(s).append(System.lineSeparator());
}
现在,检查searchString
在lineInFile
用contains
StringBuilder searchString = new StringBuilder();
builder1.append("line one");
builder1.append(System.lineSeparator());
builder1.append("line two");
System.out.println(lineInFile.toString().contains(searchString));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句