Right now I'm using Java API to create file object from resource:
new File(getClass().getResource('/resource.xml').toURI())
Is there any more idiomatic/shorter way to do that in Groovy using GDK?
File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file. getAbsolutePath(); System.
Since the path changes machine to machine, you need to use a variable / project level property, say BASE_DIRECTORY, set this value according to machine, here "/home/vishalpachupute" and rest of the path maintain the directory structure for the resources being used. Regards, Rao.
Depending on what you want to do with the File
, there might be a shorter way. Note that URL has GDK methods getText()
, eachLine{}
, and so on.
Illustration 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
Illustration 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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With