Shortest way to get File object from resource in Groovy

23,461

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()
Share:
23,461
Michal Kordas
Author by

Michal Kordas

I believe that being a truly good QA means being first of all software developer that is capable of delivering production-quality code with additional quality-related skills. I'm passionate about Java, Groovy, JVM and fancy tools that help to test code in smart, fluent and expressive way. I'm Agile and Scrum evangelist and my main area of interest is Agile Testing. I love bringing feedback loops to the micro-level. I practice test-driven development, evolutionary design, analysis brought to minimal cycle, acceptance test-driven development, three agile amigos, being business-centric to deliver solutions based on outside-in behavior-driven development technique which are continuously deployed to satisfy client as soon and as often as possible.

Updated on July 09, 2022

Comments

  • Michal Kordas
    Michal Kordas almost 2 years

    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?

  • Ravindranath Akila
    Ravindranath Akila over 3 years