我有一个文本文件,我试图从中搜索一个包含多行的字符串。我可以搜索单个字符串,但我需要搜索多行字符串。
我试图搜索工作正常的单行。
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
,从文件中读取每一行并使用lineSeparator
将它们附加到StringBuilder
StringBuilder lineInFile = new StringBuilder();
while((s=br.readLine()) != null){
lineInFile.append(s).append(System.lineSeparator());
}
现在使用contains
检查lineInFile
中的searchString
StringBuilder searchString = new StringBuilder();
builder1.append("line one");
builder1.append(System.lineSeparator());
builder1.append("line two");
System.out.println(lineInFile.toString().contains(searchString));
关于java - 在文本文件中搜索多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56511964/