Download Scripting in Java - My E-Books Web Directory
Transcript
428
SCRIPTING
Listing 9.28
IN JAVA
Continued
public class ContextWriterTest {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName(“groovy”);
engine.getContext().setWriter(
new FileWriter(“C:\\out.log”)
);
engine.eval(
new FileReader(
“net/scriptinginjava/ch9/write.groovy”
)
);
engine.getContext().getWriter().close();
}
}
In this example, we redirected the output of the evaluated script
to the file named C:\out.log. If we evaluate the following
script with the program in Listing 9.28, you can expect that the
text printed with the println Groovy command will be written
in the specified file:
println(“””This text should be written to the file \
, not console”””);
In the same manner, you can redirect the script’s standard
input and standard error streams using the setReader() and
setErrorWriter() methods, respectively. Of course, you could
use other resources with their reader and writer objects, instead
of files.
Code Generation
You are meant to use the Scripting API as a general scripting
framework that enables a unique interface to various engines.
Thus, it provides some basic script generation methods. I mentioned earlier that the ScriptEngineFactory interface provides
basic metadata that describes certain engine implementations.
Besides that interface, three additional mechanisms—
getOutputStatement(), getMethodSyntaxCall(), and
getProgram()—could help application developers to create
basic script constructs that are usually found in programming
languages. In this section, I walk you through these mechanisms.