import java.io.File;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class 执行JS文件 {
public static void main(String[] args) {
try {
执行JS文件 engine = new 执行JS文件();
engine.exeFunAdd(100, 200);
} catch(Exception e) {
e.printStackTrace();
}
}
public String getPath() {
File f = new File("");
return f.getAbsolutePath() + "/js/";
}
public void exeFunAdd(int a ,int b) {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine jsEngine = sem.getEngineByName("javascript");
try {
jsEngine.eval(new FileReader(getPath()+"funs.js"));
} catch (Exception e) {
e.printStackTrace();
}
Invocable invocableEngine = (Invocable)jsEngine;
try {
Object ret = invocableEngine.invokeFunction("add", a,b);
System.out.println(ret);
} catch (Exception e) {
}
}
}
在目录下有个js目录下面有个funs.js
function add(a, b) {
return a+b;
}
</script>