Running external Groovy scripts in our Java or Groovy application is easy to do. For example, we can use GroovyShell to evaluate Groovy code in our applications. If our script contains print methods like println, we can redirect the output of these methods. The Script class, which is a base class to run script code, has an implementation for the print, printf and println methods. The implementation of the method is to look for a property out, either as part of a Script subclass or in the binding added to a Script class. If the property out is available, then all calls to the print, printf, and println methods are delegated to the object assigned to the out property. When we use a PrintWriter instance, we have such an object, but we could also write our own class with an implementation for the print methods. Without an assignment to the out property, the fallback is to print on System.out.

In the following example, we have an external script defined with the variable scriptText, but it could also be a file or other source with the contents of the script we want to run. We assign our own PrintWriter that encapsulates a StringWriter to capture all invocations to the printmethods: