Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to get File object from resource in Groovy

Tags:

file

groovy

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?

like image 778
Michal Kordas Avatar asked Aug 31 '16 09:08

Michal Kordas


People also ask

How do you find the absolute path to a file in the resources folder of your project?

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.

How do I set the path of a file in Groovy?

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.


1 Answers

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()
like image 159
Michael Easter Avatar answered Sep 30 '22 21:09

Michael Easter