我制作了一些 .txt
文件,其中只包含一种 JavaScript 方法。例如code.txt
的内容是:
function method(){
return 4;
}
现在我想读取特定文件并执行java脚本代码
这是我尝试过的:
public class read {
public static void main(String[] args) throws IOException,ScriptException {
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("js");
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("code.txt")));
String content ="";
String code ="";
while((content = bufferedReader.readLine())!=null){
code+=content;
}
scriptEngine.eval(code);
}
}
我想从 method()
获取结果并检查返回值是否为 4