Load js (Javascript) file in java in Nashorn Javascript (js) Engine in Java 8

Program/ Example of Nashorn Javascript (js) Engine in Java 8 - Load js (Javascript) file in java>

1) Create script engine by using
new ScriptEngineManager().getEngineByName("nashorn");
2) And use eval method of engine to load js file and pass the location of js file >
  • engine.eval(new FileReader("E:/pocJmse/myNashornJavaScript.js"));
  • engine.eval("load('E:/pocJmse/myNashornJavaScript.js')");
package nashorn1;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Nashorn_LoadJavaScript {
   public static void main(String[] args) throws ScriptException, FileNotFoundException, NoSuchMethodException {
          System.out.println("In java - START");
          // Get nashorn javascript engine
          ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
            System.out.println("In java - Load js (Javascript)");

          // Pass the location of js file
          //engine.eval(new FileReader("E:/pocJmse/myNashornJavaScript.js"));
            System.out.println("In java - Javascript was loaded successfully");
            System.out.println("In java - FINISH");
In java - START
In java - Load js (Javascript)
In myNashornJavaScript.js
In java - Javascript was loaded successfully
In java - FINISH

E:/pocJmse/myNashornJavaScript.js looks like this >
print('In myNashornJavaScript.js');
//Write javascript code in it / See below examples

Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.

Must read for you :