Поиск многострочной строки в текстовом файле - PullRequest
4 голосов
/ 09 июня 2019

У меня есть текстовый файл, из которого я пытаюсь найти строку, которая имеет несколько строк. Одна строка, которую я могу искать, но мне нужно искать строку из нескольких строк.

Я попытался найти одну строку, которая работает нормально.

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

Ответы [ 5 ]

1 голос
/ 09 июня 2019

Почему бы вам просто не нормализовать все строки в файле до одной строковой переменной, а затем просто посчитать количество вхождений ввода в файле. Я использовал 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();
}

Используйте класс StringBuilder для эффективной конкатенации строк.

1 голос
/ 09 июня 2019

Попробуйте,

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();
}
1 голос
/ 09 июня 2019

Используйте для этого 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));
0 голосов
/ 09 июня 2019

Попробуйте с помощью 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);
0 голосов
/ 09 июня 2019

Более сложное решение по умолчанию 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...