Java ScriptEngineManager
ScriptEngineManager implements ScriptEngine classes. ScriptEngineManager holds key and value pair and stores the state of an object which is shared the engines created by the Manager. ScriptEngineManager uses the service provider technique to itemize implementations of ScriptEngineFactory.
Binding between the key and value pairs are traditionally referred to as the “Global Scope” that is available to all instances of ScriptEngine created by theScriptEngineManager. Value binded with the keys are made available to all the scripts.
ScriptEngineManager offers a method which returns arrays of these factories that includes few utilities on basis of mime type, languate name and file extensions.
import javax.script.*;
import java.io.*;
public class FileScript
{
public static void main(String args[])
{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName(”javascript”);
/*if(args.length!=1)
{
System.out.print(”Insufficient arguments”);
System.exit(0);
}*/
FileReader reader = null;
try
{
reader = new FileReader(args[0]);
}
catch(FileNotFoundException e1)
{
e1.printStackTrace();
}
try
{
engine.eval(reader);
}
catch(ScriptException e)
{
e.printStackTrace();
}
}
}
Note: Take the below code and save it as sample.js extension and run the above java code with the sample.js as run time argument for java interpreter
Eg: java FileScript sample.js
function hello()
{
println(”Hello from Function”);
}
for(i=0;i<5;i++)
{
print((i+1) + ” ” )
hello()
}