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

3

我有一个文本文件,想要查找其中包含多行的字符串。我可以查找单行字符串,但需要查找多行字符串。

我尝试过搜索单行字符串,结果正常。

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

如果两行不相邻会怎样? - Ryuzaki L
只有当行是相邻的时,才需要搜索。如果不是相邻的行,则不需要搜索。 - Janny
第一行
第二行
第三行
第四行
这些是您从文件中读取的搜索值,还是您在不同的地方拥有搜索值并在文件内进行搜索?
- Tenusha Guruge
5个回答

1
使用 StringBuilder 完成此操作,从文件中读取每一行并将其附加到 StringBuilder 中,使用 lineSeparator
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));

我正在搜索一个文本文件,行数不固定,可能有多行。在这种情况下,您认为这样做是否可行? - Janny
是的,请查看我的代码,直到您没有文件中的所有行,您如何检查行是否存在? @Janny - Ryuzaki L
我明白你的意思,但在实际应用中,我不应该像“第一行”,“第二行”这样硬编码数值。有什么想法吗? - Janny
它们需要从某个地方读取,对吧?如何获取输入行以在文件中搜索?@Janny - Ryuzaki L
1
你说的“不确定”是什么意思?你需要从某个地方获取内容以在文件中搜索,对吗?如果你需要从另一个文件中读取它,请将其读入另一个 StringBuilder。@Janny - Ryuzaki L
让我们在聊天中继续这个讨论 - Janny

0
为什么不将文件中的所有行都规范化为一个字符串变量,然后只需计算该输入在文件中出现的次数即可。我使用了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 类来进行高效的字符串拼接。

文件太长了,把它们归一化为一个变量是个好主意吗? - Janny
是的,那肯定不是一个好主意。你可以使用 StringBuilder 不断追加内容,而不是将它存储在 String 变量中,因为 String 赋值很慢。确定它是否有效的最好方法是运行它并检查结果。如果把所有东西都加载到内存中是一个问题,那么我可以想到一些边界情况可能会带来问题。 - Shababb Karim
1
最好的方法是使用最简单的解决方案,如果需要的话再进行优化。 - Shababb Karim

0

尝试使用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);

只有一个字符串而不是两个。单个字符串包含多行。 - Janny
String.join(System.lineSeparator(), s1, s2) == "line two" + "\n" + "line three"将s1和s2连接起来,使用系统的换行符分隔,结果应该等于"line two" + "\n" + "line three"。 - ivarkol

0

更为复杂的解决方案,使用默认的 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);

1
我正在尝试用Java实现。 - Janny
@Janny 这是 Java,但解决方案来自 C 书籍。 - VoidPointer

-1

试试这个,

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

我想要搜索多行字符串输入 = "第一行" + "第二行"; - Janny
line one 第一行line two 第二行 - Janny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接