JAVA 读取本地js文件

前提条件:本地有这个js文件,文件中定义了street变量。亲测可以使用。
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Test {
    public static void main(String[] args) throws Exception{
        /*获取执行JavaScript的执行引擎*/
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        /*为文件注入全局变量*/
        Bindings bindings = engine.createBindings();
        /*设置绑定参数的作用域*/
        engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

        // 获得js文件
        engine.eval(new FileReader("D:/leqian_git/leqian/src/main/webapp/static/js/agri"+"/streets.js"));
        System.out.println(bindings.get("street"));
        Map,Object> map = (Map) bindings.get("street");
        List list = new ArrayList<>();
        for (Map.Entry entry:map.entrySet()){
            District district = new District();
            Map tempmap = (Map)entry.getValue();
            district.setName(String.valueOf(tempmap.get("name")));
            district.setCode(Integer.parseInt(String.valueOf(tempmap.get("code"))));
            district.setPid(0);
            district.setLevel(0);
            list.add(district);
        }
        
        System.out.println(list);
    }
}

你可能感兴趣的:(Java,面试,数组)