RhinoJsFile.java - Running JavaScript Code from File

Q

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

✍: FYIcenter

A

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

Prepre 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!

 

Using Rhino JavaScript Library in Java Programs

⇒⇒FAQ for Rhino JavaScript Java Library

2017-08-08, 234👍, 0💬