从Groovy中的资源获取File对象的最短方法

时间:2016-08-31 09:36:09

标签: file groovy

现在我正在使用Java API从资源创建文件对象:

new File(getClass().getResource('/resource.xml').toURI())

使用GDK在Groovy中有没有更惯用/更短的方法?

1 个答案:

答案 0 :(得分:12)

根据您对File的要求,可能会有更短的方式。请注意URL has GDK methods getText()eachLine{}等。

插图1:

def file = new File(getClass().getResource('/resource.xml').toURI())
def list1 = []
file.eachLine { list1 << it }

// Groovier:
def list2 = []
getClass().getResource('/resource.xml').eachLine {
    list2 << it
}

assert list1 == list2

插图2:

import groovy.xml.*
def xmlSlurper = new XmlSlurper()
def url = getClass().getResource('/resource.xml')

// OP style
def file = new File(url.toURI())
def root1 = xmlSlurper.parseText(file.text)

// Groovier:
def root2 = xmlSlurper.parseText(url.text)

assert root1.text() == root2.text()