19

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?

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
  • What are you asking? Is there a classpath resource named `resource.xml`, which you want to copy to a file? Or does such a file exist on disk? – AbuNassar Aug 31 '16 at 14:20
  • I want just `java.io.File` handle to classpath resource named `resource.xml` – Michal Kordas Aug 31 '16 at 15:26
  • What about `'/resource.xml' as File`? – Opal Sep 01 '16 at 10:22
  • @Opal then I get `java.io.FileNotFoundException: (The system cannot find the file specified)` as it doesn't look up through resources, just project root file – Michal Kordas Sep 01 '16 at 14:11
  • If you made this file a classpath resource, that implies that you want it compiled into your `bin/` directory, or the JAR. If you want to load it as a file, then it's probably in `src/main/resources`, and you'd have to prepend this to the file name above. Basically, you're trying to do something self-contradictory. – AbuNassar Sep 09 '16 at 17:16
  • @TonyNassar it's just test resource used to test API that requires `File`. I cannot simply say it's in `src\test\resorces` as I have multimodule project – Michal Kordas Sep 09 '16 at 17:30

1 Answers1

33

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()
Michael Easter
  • 23,733
  • 7
  • 76
  • 107