jsファイルを実行する

サンプルだとprint()とかが定義されていなかったりするので。


public class RhinoRunner {

public static void main(String[] args) {
try {
RhinoRunner runner = new RhinoRunner();
runner.run();
} catch (Exception e) {
e.printStackTrace();
}
}

public void run() throws IOException {
String filename = "foo.js";
FileReader filin = new FileReader(filename);
BufferedReader bufin = new BufferedReader(filin);

try {
runScript(bufin, filename);
} finally {
bufin.close();
filin.close();
}
}

public void runScript(Reader in, String filename) throws IOException {
Context cx = Context.enter();

try {
Script script = cx.compileReader(in, filename, 1, null);
Global global = new Global();
ShellContextFactory factory = new ShellContextFactory();
global.init(factory);
Object result = script.exec(cx, global);

if (result != Context.getUndefinedValue())
System.err.println(Context.toString(result));
} finally {
Context.exit();
}
}
}