在文本文件中搜索(具有特定模式)

时间:2017-08-01 11:04:18

标签: java search text

文本文件如下所示:

    keyword12x:
    =========
    Acon:
    a1
    x2
    z3
    Bcon:
    c1
    e2
    w3
    r4

依此类推......(文件中始终存在相同的sheme和很多关键字)

我需要一个功能,我可以传递 keyword12x 以及信号 类型 寻找通过文本文件搜索并返回相应的Acon或Bcon信号

Exaple声明:

public string searchKey(string keyword, string type){
....
}

这样的电话:

search("keyword12x", "Acon")

输出:

a1
x2
z3

(type = Bcon显然会给出c1,e2,w3,r4)

编辑: 这就是"我有" ..(它不是我想要的,仅用于测试porpose) 你可以看到它正在搜索" keyword12x"线,我被困在那里。

import java.io.File;
import java.util.Scanner;
public class ReadText
{
  public static void main(String[] args) throws Exception
  {
    File file =
      new File("C:\\test.txt");
    Scanner sc = new Scanner(file);

    while (sc.hasNextLine()){
    String line = sc.nextLine();
    if(line.contains("keyword12x")){
        System.out.println(line);
    }
  }
}
}

EDIT2:

> step by step "in english":
> 1. go trough lines
> 2. untill you find "keyword12x"
> 3. keep going through lines (from that point !)
> 4. find "Acon:"
> 5. go next line
> 6. start printing out and go next line (loop)
> 7. until line = "Bcon:" appears
> 8. go next line
> 9. start printing out and go next line (loop)
> 10. untill an empty line appears

EDIT3: 让简历:我想搜索包含关键字的行(附加':'附加),然后(在该行之后)搜索包含给定类型的行(后面跟着' :')然后收集以下所有行,但不包括以'结尾的行:'或空行。 [摘自@Carlos Heuberger]

1 个答案:

答案 0 :(得分:3)

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Demo
{
static String readLine = "";

String ch ;

static File f = new File("/home/admin1/demoEx");

public String searchKey(String keyword, String type) throws IOException
{
    ch = type.toLowerCase().substring(0, 1);

    BufferedReader b = null;
    try {
        b = new BufferedReader(new FileReader(f));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Reading file using Buffered Reader");

    while ((readLine = b.readLine()) != null) 
    {
        if(readLine.contains(ch))
        {
            System.out.println(readLine);
        }
    }

    return readLine;
}

public static void main(String args[]) 
{
    try {

        String x = (new Demo()).searchKey("keyword12x","Bcon");

    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

尝试这个。