Subscribe to RSS feed

Posts tagged with "JAVA"

Use JavaScript from inside Java

,

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.

// 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);

February 2012
M T W T F S S
January 2012March 2012
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29