想要从特定点开始阅读文件

时间:2013-03-20 19:15:26

标签: java

我有一个包含日志打印输出的文件,我想读取某些行,从行的中间到结尾的某个点,然后移动到符合条件的下一行。 我想从RULE EXECUTING开始读到行尾,然后检查它的下一行是否有RULE EXECUTING如果没有将它跳到下一行,如果确实有RULE EXECUTING则从该点复制到行尾

 FILE SAMPLE

2013-02-14 09:26:20:078 [main] DEBUG sne.ABC.hdhdh.jfjjfj.jkfjfjd.jdsd - RULE EXECUTING --> CMNETSL.hdjjjdlskdnlskd.jgfkdflkdfl_Translation
2013-02-14 09:28:00:312 [main] DEBUG moc.uty.lweifoisd.sfsd.kjfdnkjs.RulesetInvoker  - Rudejgfjkgjf:  After invoking: CMNETSLO
2013-02-14 09:26:20:421 [main] DEBUG sne.ABC.hdhdh.jfjjfj.jkfjfjd.jdsd - RULE EXECUTING --> sne.ABC.hdhdh.jfjjfj.jkfjfjd.jdsd


what I want to get from the line would look like this

RULE EXECUTING --> CMNETSL.hdjjjdlskdnlskd.jgfkdflkdfl_Translation
RULE EXECUTING --> sne.ABC.hdhdh.jfjjfj.jkfjfjd.jdsd

3 个答案:

答案 0 :(得分:0)

所以,比如:

BufferedReader br = new BufferedReader(new FileReader("mylog.log"));

String line;
int idx;
while((line = br.getLine()) != null)
  if((idx = line.indexOf("RULE EXECUTING --> ")) != -1)
    System.out.println(line.substring(idx));

我没有在ide中尝试或编译它,但我认为你可能会得到这个想法。

答案 1 :(得分:0)

Scanner s = new Scanner(new File("log.txt")); // read file using scanner line by line

while(s.hasNextLine())
{

    String nextLine = s.nextLine(); 

    if(nextLine.startsWith("RULE EXECUTING")) //check if line starts with the key word
    {
              // do whatever you want to do 
    }
}

答案 2 :(得分:0)

您必须为此读取整个文件,使用FileReader并读取行的文件行,在每个文件中搜索子字符串“RULE EXECUTING”。如果找到,请使用substring方法输出或以其他方式处理子字符串。重复直到文件完成 - 最重要的是 - 关闭文件。

以下是完整的代码示例:

    BufferedReader reader = null;
    try {
        //open file
        reader = new BufferedReader(new FileReader("example.log"));

        int index;

        //read first line
        String line = reader.readLine();

        //go through the entire file line for line
        while (line != null) {

            //look for substring in line
            index = line.indexOf("RULE EXECUTING");
            if(index >= 0 ) {
                //substring found, write result to stdout
                System.out.println(line.substring(index));
            }

            //read next line
            line = reader.readLine();
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            //always close file readers!
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }