【问题标题】:Search in a text file (with specific pattern)在文本文件中搜索(具有特定模式)
【发布时间】:2017-08-01 11:04:18
【问题描述】:

文本文件如下所示:

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

等等...(总是相同的sheme和文件中的很多关键字)

我需要一个可以传递 keyword12x 和我正在寻找的信号 type 的函数它搜索文本文件并返回相应的 Acon 或 Bcon 信号

示例声明:

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 的总结]

【问题讨论】:

  • 那么你具体坚持哪一部分?你试过自己写这个方法吗?
  • 是的,尝试了很多,但我总是坚持我只能找到实际的“keyword12x”行。我不知道如何使用行号或其他(?)跳转到相应的信号
  • 告诉我们你已经尝试过什么我们不会做你的功课
  • 答案是:你不能。你必须检查每一行。或者尝试将信号的行号存储在某处,然后跳过 X 行直接进入它。
  • 我用“我所拥有的”编辑了我的帖子。只是认为它没有任何用处,因为我觉得这次尝试完全被困住了......

标签: java search text


【解决方案1】:
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();
    }
}
}

试试这个。

【讨论】:

  • 谢谢,我看到你在那里做了什么,实际上我已经看过缓冲阅读,因为性能优势,但这仍然不能解决我的主要问题,因为它实际上并没有使用关键字.遗憾的是,检查第一封信也不适用于我的真实文件。我必须以某种方式实现它,就像我在原始帖子的 EDIT2 中写下来的那样......
猜你喜欢
  • 2020-05-03
  • 2017-12-01
  • 2021-09-16
  • 1970-01-01
  • 2016-05-03
  • 2018-06-01
  • 1970-01-01
  • 2015-12-25
  • 2014-12-14
相关资源
最近更新 更多