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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s