Executing scripts written in a file using java

This post explain how to execute javascript code stored in a file.

We create an instance of FileReader representing the physical file and pass it to eval method of an instance of ScriptEngine.

Please refer to previous posts to know more about ScriptEngine and ScriptEngineManager

The javascript code in the file that has to be executed is as shown below.

test.js


print("This is hello from test.js");

Main Class


package package1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Demo2 {
    public static void main(String[] args) throws FileNotFoundException, IOException, ScriptException {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
        File file = new File("test.js");
        try(FileReader fr = new FileReader(file);) {
            scriptEngine.eval(fr);
        }
    }
}

Output

Hello, World

Leave a Reply