现在我正在使用Java API从资源创建文件对象:
new File(getClass().getResource('/resource.xml').toURI())
使用GDK在Groovy中有没有更惯用/更短的方法?
答案 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()