Executing a Script Stored in a File - Java Scripting

Java examples for Scripting:Run Script

Description

Executing a Script Stored in a File

Demo Code

import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main {
  public static void main(String[] args) {
    String scriptFileName = "helloscript.js";
    Path scriptPath = Paths.get(scriptFileName);

    if (! Files.exists(scriptPath) ) {
      System.out.println(scriptPath.toAbsolutePath() +
        " does not exist.");
      return;//  w  ww  .j a v  a  2  s  . c o  m
    }
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    try {
      Reader scriptReader = Files.newBufferedReader(scriptPath);
      engine.eval(scriptReader);
    }
    catch (IOException | ScriptException e) {
      e.printStackTrace();
    }
  }
}

Related Tutorials