Java examples on javax.script
- How do I access Java object from a script?
- How do I create a ScriptEngine for JavaScript?
- How do I get a ScriptEngine by language name and version?
- How do I call a specific function of a script?
- How do I evaluate or execute a script file?
- How do I evaluate a simple script?
- How do I import Java package in script?
- How do I modified Java object in script?
- How do I get the supported scripting engine?
- How do I get ScriptEngine by engine name?
How do I evaluate or execute a script file?
This example demonstrate how to evaluate script that stored on a file. As we know that the eval() method can also accept a Reader object we can then read the script file using FileReader and pass it as the parameter to the eval() method of the ScriptEngine for further evaluation.
package org.kodejava.example.script;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.File;
import java.io.Reader;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class EvalScriptFile {
public static void main(String[] args) {
//
// Obtaining ECMAScript / JavaScript ScriptEngine.
//
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("ECMAScript");
try {
//
// Create an instance of File object that point to our
// scripting file. An create a FileReader to read the
// file to be passed to the ScriptEngine.eval() method.
//
// The file need to be placed in the same folder with
// our class so it enable to read it. We can define the
// full path to the file also to make easier for the
// Reader to find it.
//
File script = new File("helloworld.js");
Reader reader = new FileReader(script);
engine.eval(reader);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ScriptException e) {
e.printStackTrace();
}
}
}