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

标签 file groovy

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

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

在 Groovy 中使用 GDK 是否有更多惯用/更短的方法来做到这一点?

最佳答案

取决于您想用 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()

关于file - 从 Groovy 中的资源获取 File 对象的最短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39245934/

相关文章:

c - 程序只读取 C 中 Matrix 的第一行

c++ - 在 Qt C++ 中使用文件系统

c - 为什么不能从 C 语言的文件中打印整数

android - 使用 Intent 打开下载的文件

java - 在 groovy 中模拟扩展的 java 类

java - Groovy 无法解析 Java 类

grails - 检查instanceOf之后的ClassCastException

ios - 在图像文件头上添加注释

Spring 4 - Autowire 通用

java - 将连续尾部输出重定向到 UI