How do I use the firstLine argument in eachLine

浪子不回头ぞ 提交于 2020-06-27 07:39:09

问题


I can't seem to make eachLine skip the first line, according to this there is an integer argument that can be passed to eachLine but I can't figure out the syntax

http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html#eachLine(int, groovy.lang.Closure)

#doesn't work
new FileReader('myfile.txt').eachLine firstLine=2,{
       line-> println line
}
#nope
new FileReader('myfile.txt').eachLine(2){
       line-> println line
}

回答1:


I think you are misunderstanding what the 'firstLine' parameter is used for. From the docs:

firstLine - the line number value used for the first line

Basically this means that this number will identify what the first line is. It always goes through each line in the file.

So for the following code:

new FileReader('c:/users/chris/desktop/file.txt').eachLine(4){line, number-> 
    println "$number $line"
}

It would print out:

4 line1

5 line2

6 line3




回答2:


To skip first line use return. It's works like continue in standard loops.

new FileReader('myfile.txt').eachLine { line, number ->
    if (number == 1)
        return // continue

    println "$number: $line"
}



回答3:


To expand upon @Michal's answer, for a general case (as opposed to a single line), you could do:

linesToSkip = 100
someFile.eachLine { line, lineNumber ->
    if (lineNumber < linesToSkip) { return }  // Skip previously read lines
    println "${line}"
}



回答4:


i was used readline x times before;

def arq = new FileReader('c:/users/chris/desktop/file.txt')
(0..4).each{
     arq.readLine();
}
arq.eachLine{line, number-> 
    println "$number $line"
}


来源:https://stackoverflow.com/questions/2699865/how-do-i-use-the-firstline-argument-in-eachline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!