2

我有一个包含日志打印输出的文件,我想读取某些行,并从行中到行尾的某个点读取并移至符合条件的下一行。我想从 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
4

3 回答 3

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();
        }
    }
于 2013-03-20T19:36:44.733 回答
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 中尝试过或编译过它,但我认为你可能明白了。

于 2013-03-20T19:20:05.360 回答
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 
    }
}
于 2013-03-20T19:21:21.560 回答