The shortest way to get a File object from a resource in Groovy

Right now I'm using the Java API to create a file object from a resource:

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

Is there a more idiomatic / shorter way to do this in Groovy using GDK?

+4
source share
1 answer

Depending on what you want to do with File, there may be a shorter path. Note that the URL has GDK methods getText() , eachLine{}etc.

Figure 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

Figure 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()
+6
source

Source: https://habr.com/ru/post/1653114/


All Articles