Execute JavaScript file
suggest change// Required imports
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
// "nashorn" is the JDK engine from Java 8 through 14. It was removed in Java 15.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
// Load and execute a script from the file 'demo.js'
try (FileReader reader = new FileReader("demo.js")) {
engine.eval(reader);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ScriptException ex) {
// checked exception thrown by the Scripting API
ex.printStackTrace();
}
// Outcome when Nashorn is present:
// 'Script from file!' printed on standard output.
// After Nashorn is removed, getEngineByName returns null and eval throws NullPointerException.
demo.js:
print('Script from file!');
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents