Java Reference
In-Depth Information
Sending Scripts Output to a File
You can customize the input source, output destination, and error output destination of
a script execution. You need to set appropriate reader and writers for the
ScriptContext
that is used to execute a script. The following snippet of code will write the script output
to a file named
jsoutput.txt
in the current directory:
// Create a FileWriter
FileWriter writer = new FileWriter("jsoutput.txt");
// Get the default context of the engine
ScriptContext defaultCtx = engine.getContext();
// Set the output writer for the default context of the engine
defaultCtx.setWriter(writer);
The code sets a custom output writer for the default context of the
ScriptEngine
that
will be used during the execution of scripts that use the default context. If you want to
use a custom output writer for a specific execution of a script, you need to use a custom
ScriptContext
and set its writer.
■
setting a custom output writer for a
ScriptContext
does not affect the destination
of the standard output of the Java application. to redirect the standard output of the Java
application, you need to use the
System.setOut()
method.
Tip
Listing 3-7 shows how to write output of a script execution to a file named
jsoutput.txt
.
The program prints the full path of the output file on the standard output. You may get
a different output when you run the program. You need to open the output file in a text
editor to see the script's output.
Listing 3-7.
Writing the Output of Scripts to a File
// CustomScriptOutput.java
package com.jdojo.script;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
Search WWH ::
Custom Search