代码之家  ›  专栏  ›  技术社区  ›  ScArcher2

使用reader.eachline读取BufferedInputStream时,如何保持行号计数?

  •  1
  • ScArcher2  · 技术社区  · 14 年前

    当使用每个行读取BufferedInputStream时,如何跟踪我所使用的行号?

    def input = new GZIPInputStream(new FileInputStream(f))
    def reader = new BufferedReader(new InputStreamReader(input))
    reader.eachLine {
        line ->if(line.contains(searchString)){
            println "${f} - ${line}"
        }
    }
    
    1 回复  |  直到 14 年前
        1
  •  8
  •   sschuberth    7 年前

    The closure you pass to eachLine can also take 2 parameters. First being the line of data and the second being the line number.

    ....
    ....
    reader.eachLine { line, lineNumber ->
        if(line.contains(searchString)) {
            println "${lineNumber} - ${line}"
        }
    }
    

    GDK Doc for InputStream eachLine method .