1.javascript代码:a.js:
function test(){
var a = 3;
var b = 4;
println("invoke a.js file:" + (3+4));
}
test();
2.java代码中执行a.js:
package com.buaa.testRhino;
import java.io.FileReader;
import java.net.URL;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Demo01 {
public static void main(String[] args) {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("javascript");
//执行javascript文件a.js
URL url = Demo01.class.getClassLoader().getResource("a.js");
FileReader reader;
try {
reader = new FileReader(url.getPath());
engine.eval(reader);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}