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 creates the following output:
StringBuffer contains: This output will go to the string writer.