简体   繁体   English

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

[英]Search for multiline String in a text file

I have a text file from which i am trying to search for a String which has multiple lines. 我有一个文本文件,我试图搜索一个有多行的字符串。 A single string i am able to search but i need multi line string to be searched. 我能够搜索的单个字符串,但我需要搜索多行字符串。

I have tried to search for single line which is working fine. 我试图寻找工作正常的单线。

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();
}

And below are the file contents. 以下是文件内容。

line one  
line two  
line three  
line four

Use the StringBuilder for that, read every line from file and append them to StringBuilder with lineSeparator 使用StringBuilder ,从文件中读取每一行,并使用lineSeparator将它们附加到StringBuilder

StringBuilder lineInFile = new StringBuilder();

while((s=br.readLine()) != null){
  lineInFile.append(s).append(System.lineSeparator());
}

Now check the searchString in lineInFile by using contains 现在使用contains检查searchString中的lineInFile

StringBuilder searchString = new StringBuilder();

builder1.append("line one");
builder1.append(System.lineSeparator());
builder1.append("line two");

System.out.println(lineInFile.toString().contains(searchString));

Try This, 试试这个,

public static void main(String[] args) throws IOException {
    File f1 = new File("./src/test/test.txt");
    FileReader fr = new FileReader(f1);
    BufferedReader br = new BufferedReader(fr);
    String input = "line one";
    int count = 0;

    String line;
    while ((line = br.readLine()) != null) {
        if (line.contains(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();
}

Why don't you just normalize all the lines in the file to one string variable and then just count the number of occurrences of the input in the file. 为什么不将文件中的所有行标准化为一个字符串变量,然后只计算文件中输入的出现次数。 I have used Regex to count the occurrences but can be done in any custom way you find suitable. 我使用Regex来计算事件的数量,但可以用你认为合适的任何自定义方式来完成。

public static void main(String[] args) throws IOException 
{
        File f1=new File("test.txt"); 
        String[] words=null;  
        FileReader fr = new FileReader(f1);  
        BufferedReader br = new BufferedReader(fr); 
        String s;     
        String input="line one line two"; 

        // here i want to search for multilines as single string like 
        //   String input ="line one"+
        //                 "line two";

        int count=0;
        String fileStr = "";
        while((s=br.readLine())!=null)   
        {
            // Normalizing the whole file to be stored in one single variable
            fileStr += s + " ";
        }

        // Now count the occurences
        Pattern p = Pattern.compile(input);
        Matcher m = p.matcher(fileStr);
        while (m.find()) {
            count++;
        }

        System.out.println(count); 

        fr.close();
}

Use StringBuilder class for efficient string concatenation. 使用StringBuilder类进行高效的字符串连接。

More complicated solution from default C (code is based on code from book «The C programming language» ) 来自默认C的更复杂的解决方案(代码基于«C编程语言»中的代码)

final String searchFor = "Ich reiß der Puppe den Kopf ab\n" +
        "Ja, ich reiß' ich der Puppe den Kopf ab";

int found = 0;

try {
    String fileContent = new String(Files.readAllBytes(
        new File("puppe-text").toPath()
    ));

    int i, j, k;
    for (i = 0; i < fileContent.length(); i++) {
        for (k = i, j = 0; (fileContent.charAt(k++) == searchFor.charAt(j++)) && (j < searchFor.length());) {
            // nothig
        }

        if (j == searchFor.length()) {
            ++found;
        }
    }
} catch (IOException ignore) {}

System.out.println(found);

Try with Scanner.findWithinHorizon() 试试Scanner.findWithinHorizo​​n()

String pathToFile = "/home/user/lines.txt";
String s1 = "line two";
String s2 = "line three";

String pattern = String.join(System.lineSeparator(), s1, s2);

int count = 0;
try (Scanner scanner = new Scanner(new FileInputStream(pathToFile))) {
  while (scanner.hasNext()) {
    String withinHorizon = scanner.findWithinHorizon(pattern, pattern.length());
    if (withinHorizon != null) {
      count++;
    } else {
      scanner.nextLine();
    }

  }
} catch (FileNotFoundException e) {
  e.printStackTrace();
}
System.out.println(count);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM