groovy读取文件获取某些行,然后将每个检索到的行拆分为多个部分

Ray*_*Ray 2 groovy

我认为在Groovy中必须有一种优雅的方式来执行此操作(即一项常见任务).有人可以给一个代码片段吗?这个问题与这个条目有关:groovy这个基本闭包有什么问题?.

...看起来像使用闭包的File.filterLine()方法是一个好的开始,但是一旦你有了这些线,将它们分开的优雅方法是什么?例如,假设有人试图在逗号分隔文件(CSV)中挑选某些行,然后将这些行拆开.

ata*_*lor 5

如果您不关心效率或将整个文件加载到内存中,这将起作用:

new File("myFile.csv").readLines().findAll { it =~ ~/regexp/ }*.tokenize(",")
Run Code Online (Sandbox Code Playgroud)

Groovy似乎没有一种非常好的方法来过滤流中的行而不将文件加载到内存中.以下是使用小型支持类的一种方法:

new LineFilter(new File("myFile.csv").newReader(), ~/regexp/)*.tokenize(",")

@groovy.transform.Canonical
class LineFilter implements Iterator {
    def source
    def filter
    def peek = []

    String next() {
        while (true) {
            if (peek) {
                return peek.pop()
            }
            def nextLine = source.readLine()
            if (nextLine == null) {
                throw new NoSuchElementException()
            } else if (nextLine =~ filter) {
                return nextLine
            }
        }
    }

    boolean hasNext() {
        try {
            if (!peek) {
                peek.push(next())
            }
        } catch (NoSuchElementException e) {
            return false
        }
        true
    }

    void remove() { throw new UnsupportedOperationException() }
}
Run Code Online (Sandbox Code Playgroud)