(Quick Reference)

11.1 Locating Classpath Resources - Reference Documentation

Authors: Andres Almiray

Version: 1.2.0

11.1 Locating Classpath Resources

Resources can be loaded form the classpath using the standard mechanism provided by the Java runtime, that is, ask a ClassLoader instance to load a resource URL or obtain an InputStream that points to the resource.

But the code can get quite verbose, take for example the following view code that locates a text file and displays it on a text component

scrollPane {
    textArea(columns: 40, rows: 20,
        text: this.class.classLoader.getResource('someTextFile.txt').text)
}

In order to reduce visual clutter, also to provide an abstraction over resource location, both GriffonApplication and GriffonArtifact have a set of methods that simply working with resources. Those methods are provided by ResourceHandler:

  • URL getResourceAsURL(String resourceName)
  • InputStream getResourceAsStream(String resourceName)
  • List<URL> getResources(String resourceName)

Thus, the previous example can be rewritten in this way

scrollPane {
    textArea(columns: 40, rows: 20,
        text: app.getResourceAsURL('someTextFile.txt').text)
}

In the future Griffon may switch to a modularized runtime, this abstraction will shield you from any problems when the underlying mechanism changes.