如果我正在阅读文件的每一行,如下所示
file.eachLine {line->
println line
}
是否可以读取闭包内的NEXT行。
例如
file.eachLine {line ->
//print next line as well if current line contains 'hooray'
if (line.find(/hooray/)!=null)
{
println "current line: ${line}"
println "next line: ${line->next}" //this is just my syntax...
}
}
答案 0 :(得分:2)
封闭没有直接支持,但如果你稍微改变一下,它很容易实现相同的逻辑:
// test script:
def f = new File("test.txt")
def currentLine
f.eachLine { nextLine ->
if (currentLine) {
if (currentLine.find(/hooray/)) {
println "current line: ${currentLine}"
println "next line: ${nextLine}"
}
}
currentLine = nextLine
}
// test.txt contents:
first line
second line
third line
fourth line
fifth hooray line
sixth line
seventh line
编辑:
如果您正在寻找Chili在下面评论过的封装,您可以随时在File上定义自己的方法:
File.metaClass.eachLineWithNextLinePeek = { closure ->
def currentLine
delegate.eachLine { nextLine ->
if (currentLine) {
closure(currentLine, nextLine)
}
currentLine = nextLine
}
}
def f = new File("test.txt")
f.eachLineWithNextLinePeek { currentLine, nextLine ->
if (currentLine.find(/hooray/)) {
println "current line: ${currentLine}"
println "next line: ${nextLine}"
}
}