简体   繁体   中英

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 lineInFile = new StringBuilder();

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

Now check the searchString in lineInFile by using contains

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.

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.

More complicated solution from default C (code is based on code from book «The C programming language» )

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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