Use JavaScript from inside Java
Wednesday, August 22, 2007 11:22:07 AM
If you are using Java 6 (or 1.6, depending on how you count), the Rhino JavaScript engine is avaialable to you in the JDK. I didn't know this, and was very happy to see that it was. You can get a Java 6 package in Ubuntu.
If you want to run a javascript file, just use this code. Remember that things from client-side javascript, like the DOM, is not available.
Simple Javascript code you can use to test that things actually works:
If you want to run a javascript file, just use this code. Remember that things from client-side javascript, like the DOM, is not available.
// JavascriptLoader.java
// How to compile: javac JavascriptLoader.java
// How to run: java JavascriptLoader JS_FILENAME
import javax.script.*;
import java.io.*;
public class JavascriptLoader {
public static void main(String args[])
{
if (args.length == 0) {
System.out.println("Please provide a js file");
return;
}
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
try {
jsEngine.eval(new FileReader(args[0]));
} catch (ScriptException ex) {
System.out.println("ScriptException");
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException");
}
}
}
Simple Javascript code you can use to test that things actually works:
for (var i = 0; i < 10; i++)
println("Looping: " + i);







