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

时间:2010-06-28 21:41:58

标签: groovy

如何在使用eachLine读取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 个答案:

答案 0 :(得分:8)

传递给eachLine的闭包也可以使用2个参数。首先是数据行,第二个是行号。

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

请参阅GDK Doc for InputStream eachLine method