How do I evaluate or execute a script file?

This example demonstrated 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.script;

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

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);

        } catch (FileNotFoundException | ScriptException e) {

Our helloworld.js file.

console.log('Hello World');

for (let i = 0; i <= 10; i++) {
    console.log(`i = ${i}`);

The output of the code snippet:

Hello World
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10

Maven Dependencies


Maven Central Maven Central


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.