时间:2021-07-01 10:21:17 帮助过:4人阅读
import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class RunScriptFile {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
try {
FileReader reader = new FileReader("testFile.js");
engine.eval(reader);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
例如要运行的js代码如下:
代码如下:
function add(a, b) {
c = a + b;
return c;
}
result = add (10, 5);
print ('Result = ' + result);
然后在shell中运行:
javac RunScriptFile.java
java RunScriptFile
生成结果如下:
Result = 15