RhinoJsFile.java - Running JavaScript Code from File


How to run JavaScript code from a file with Rhino JavaScript Java library?

✍: FYIcenter


Running JavaScript code from a file is easy. Just following the example below:

// Copyright (c) 2017 FYIcenter.com
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import java.io.*;

public class RhinoJsFile {
   public static void main(String[] args) throws Exception {
    ContextFactory f = new ContextFactory();
      Context c = f.enterContext();
    Scriptable s = c.initStandardObjects();

    FileReader js = new FileReader(args[0]);
      c.evaluateReader(s, js, null, 1, null);

Prepare your JavaScript code file, Hello.js:

var name = "FYIcenter.com";
java.lang.System.out.println("Hello, welcome to "+name+"!");

Compile and run the example program, RhinoJsFile.java:

>\fyicenter\jdk-1.8.0\bin\javac -cp \fyicenter\rhino1_7R5\js.jar RhinoJsFile.java

>\fyicenter\jdk-1.8.0\bin\java -cp .;\fyicenter\rhino1_7R5\js.jar 
   RhinoJsFile Hello.js

Hello, welcome to FYIcenter.com!


Running Examples Provided in Rhino

RhinoFunctionCall.java - Call JavaScript Function from Java

Using Rhino JavaScript Library in Java Programs

⇑⇑ FAQ for Rhino JavaScript Java Library

2017-08-08, 1785🔥, 0💬