是否可以将Context.evaluateString(...)的输出重定向到Writer?我正在寻找与jdk 6提供的类似于ScriptContext.setWriter(http://download.oracle.com/javase/6/docs/api/javax/script/ScriptContext.html#setWriter%28java.io.Writer%29)的东西。
答案 0 :(得分:0)
Rhino没有标准输入/输出的概念,因此您必须将Writer分配给某个变量。像这样:
import java.io.StringWriter;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ScriptableObject;
public class SetWriter {
public static void main(String[] args) {
Context c=Context.enter();
ScriptableObject scope = c.initStandardObjects();
StringWriter writer=new StringWriter();
ScriptableObject.putProperty(scope, "writer", writer);
String source = " writer.write('hello'); ";
c.evaluateString(scope, source, "TEST", 1, null);
System.out.println(writer.getBuffer());
}
}
或者,您在脚本中使用System.out.println,在运行脚本之前请考虑使用System.setOut。