有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何通过读取bufferedreader获得前一行的可变数量

我正在使用BufferedReader逐行读取日志文件。如果一条线与一个精确的图案匹配,我也会获得前面的线。此行号由用户输入。例如,模式是“错误”和行号3,所以我将存储错误行和前3行

 FileInputStream fInStream = new FileInputStream(fileBase);
 br = new BufferedReader(new InputStreamReader(fInStream));

 while ((line = br.readLine()) != null) {
    if(line.contains("ERROR")){
           //here, i should write previous 3 lines and then ERROR line
           bw.write(line + "\r\n");   
     }
 }

如有任何建议,将不胜感激


共 (2) 个答案

  1. # 1 楼答案

    您必须保存最后n行的读数,以便在遇到错误行时始终显示它们

    困难的部分是创建一个数据结构,以便为您跟踪最后n行

    也许你可以使用类似于这个问题的答案Looking for a circular fixed size array-based deque

    所以你的代码是这样的

    Ring ring = new Ring(n);
    while ((line = br.readLine()) != null) {
    
        if(line.contains("ERROR")){
           //note no checking to see if there are n lines 
           //currently stored in Ring maybe have to make a size() method
           // and check that
           for(int i=0; i<n; i++){
               bw.write(ring.get(i) + "\r\n"); 
           }
           bw.write(line + "\r\n");   
         }
         //add line to Ring here
          ring.push(line);
     }
    
  2. # 2 楼答案

    正如我在评论中所说,你可以跟踪用户在每一步中要求的最后几行。因此,在阅读了日志中不包含“错误”的一行之后,你会将其添加到你的记忆行列表中,如果此时记忆行列表的长度超过了用户要求的行数,则扔掉其中最早的条目

    因此,在代码中,它看起来是这样的(您可以在数据结构中使用LinkedList):

    // number of lines to print before the ERROR
    int numContextLines = // user input
    
    ...
    
    Deque<String> contextLines = new LinkedList<String>();
    while ((line = br.readLine()) != null) {
        if(line.contains("ERROR")){
            // print out all of the context lines
            for (String contextLine : contextLines) {
                bw.write(contextLine + "\r\n");
            }
            bw.write(line + "\r\n");
        } else {
            // this is not an ERROR message so store it in our list of 
            // context lines that we can print when we find an ERROR
            contextLines.addFirst(line);
    
            // if this list has gotten too long then throw away the oldest entry in it
            if (contextLines.size() > numContextLines) {
                contextLines.removeLast();
            }
        }
    }