Understand Script Contexts
ScriptEngine's setBindings() and getBindings() methods are convenient methods for accessing the ScriptContext interface's own setBindings() and getBindings() methods. ScriptContext describes a script context, which connects a Java program to a script engine. The SimpleScriptContext class implements this interface.
Essentially, a script context exposes engine and global bindings to a script engine so that a Java program can communicate with a script via script variables. Also, a script context exposes a java.io.Reader and a pair of java.io.Writers that a script engine uses for input/output. The engine bindings default to being empty. Also, the reader defaults to a java.io.InputStreamReader instance that obtains input from System.in. Finally, the writers default to java.io.PrintWriter instances that send their output to System.out and System.err.
You can replace the Reader by invoking ScriptContext's public void setReader(Reader reader) method. The current reader can be obtained by invoking public Reader getReader(). Similarly, the writer and error writer can be replaced by invoking ScriptContext's public void setWriter(Writer writer) and public void setErrorWriter(Writer writer) methods. The current writer and error writer can be obtained by invoking public Writer getWriter() and public Writer getErrorWriter().
Listing 5 presents an application that uses setWriter() to install a PrintWriter for outputting to a string instead of standard output.
Listing 5: ScriptDemo5.java
// ScriptDemo5.java import java.io.*; import javax.script.*; public class ScriptDemo5 { public static void main (String [] args) throws ScriptException { // Create a ScriptEngineManager that discovers all script engine // factories (and their associated script engines) that are visible to // the current thread's classloader. ScriptEngineManager manager = new ScriptEngineManager (); // Obtain a ScriptEngine that supports the JavaScript short name. ScriptEngine engine = manager.getEngineByName ("JavaScript"); // Redirect the engine's standard output to a StringWriter instance. StringWriter writer = new StringWriter (); PrintWriter pw = new PrintWriter (writer, true); engine.getContext ().setWriter (pw); // Evaluate a script that outputs some text. engine.eval ("println ('This output will go to the string writer.');"); // Obtain the string buffer's contents and output these contents. StringBuffer sb = writer.getBuffer (); System.out.println ("StringBuffer contains: " + sb); } }
Although you can pass any Writer to setWriter() and setErrorWriter(), the Rhino JavaScript engine requires that you pass a PrintWriter to which the ultimate destination writer is chained.
ScriptDemo5 creates the following output:
StringBuffer contains: This output will go to the string writer.