The ScriptEngineManager comes along with the package javax.script.
This is a relatively small, simple API. A ScriptEngineManager object can discover script engines through the jar file service discovery mechanism. It can also instantiate ScriptEngine objects that interpret scripts written in a specific scripting language. The simplest way to use the scripting API is as follows:
- Create a ScriptEngineManager object.
- Get a ScriptEngine object from the manager.
- Evaluate script using the ScriptEngine’s eval methods.
Now we look at the sample code.
Executing a Script from .js File:
The eval method have the FileReader object as argument.
we can create the ScriptEngineManager and get the ScriptEngine from the above code(line 4-7).
Then we add the eval method which is used to execute script from .js file.
Let us assume that we have the file named “welcome.js” with the following text:
println("Welcome to java world");
If we will run the code,this yields the output as
Welcome to java world.