现在我正在使用Java API从资源创建文件对象:
new File(getClass().getResource('/resource.xml').toURI())
Run Code Online (Sandbox Code Playgroud)
使用GDK在Groovy中有更多惯用/更短的方法吗?
Mic*_*ter 18
根据你想要做什么File,可能会有一个更短的方式.请注意,URL具有GDK方法 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
Run Code Online (Sandbox Code Playgroud)
插图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()
Run Code Online (Sandbox Code Playgroud)