java - 在文本文件中搜索多行字符串

标签 java string file bufferedreader multiline

我有一个文本文件,我试图从中搜索一个包含多行的字符串。我可以搜索单个字符串,但我需要搜索多行字符串。

我试图搜索工作正常的单行。

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/

相关文章:

c - Win API函数修改文件权限

c++ - FindFirstFile 问题无法让任何示例正常工作。

java - 如何解码字符串化的unicode?

string - BeautifulSoup Div 类返回空

java - 仅从字符串中检索给定的单词

java - 断言语句后出现 ArrayIndexOutOfBoundsException

python - 在 Python 中,如何将字符串转换为文件?

C#比较基于名称的文件列表不返回完整路径

java - 在 EclipseLink-2.5.2 中为可嵌入类配置 ID 类型时出现奇怪问题

java - 如何从现有 Java 项目中提取主类?