背景(可跳过):基本Groovy脚本引擎设置
我最近用Java写了一个轻量级的服务器轮询一个端口上的新连接,然后当客户端连接它给了他们自己的线程,直至插槽关闭。现在,一旦客户端连接,我需要做的是以特殊的方式准备XML文件请求;如果客户端请求file1.xml,则服务器需要读取file1.xml,将其解析为JSON,然后将json对象发送给客户端。
问题具体(现在开始阅读): 我需要将XML文件解析为Java中的JSON对象。我被推荐GROOVY来完成这项任务。在我的Mac和Ubuntu分区上安装是一件轻而易举的事情,但我无法使内联groovy工作,原因很可能非常微不足道。这就是我现在的测试(在这一点上,我只是试图让嵌入式常规工作):
test.groovy
output = "Hello ${input}!"
test.java
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
String[] roots = new String[] { "/home/nick/Documents" };
GroovyScriptEngine gse = new GroovyScriptEngine(roots);
Binding binding = new Binding();
binding.setVariable("input", "world");
gse.run("test.groovy", binding);
System.out.println(binding.getVariable("output"));
这两个文件都在我的/home/nick/Documents
文件夹中。当我尝试编译:
javac test.java
我得到的6个错误:
test.java:4: class, interface, or enum expected
String[] roots = new String[] { "/home/nick/Documents" };
^
test.java:5: class, interface, or enum expected
GroovyScriptEngine gse = new GroovyScriptEngine(roots);
^
test.java:6: class, interface, or enum expected
Binding binding = new Binding();
^
test.java:7: class, interface, or enum expected
binding.setVariable("input", "world");
^
test.java:8: class, interface, or enum expected
gse.run("test.groovy", binding);
^
test.java:9: class, interface, or enum expected
System.out.println(binding.getVariable("output"));
^
6 errors
我觉得我做错了什么在编译阶段。我怎样才能得到这个编译和运行?
帮助非常感谢
所以,该ScriptEngine是真的装载所有的脚本依赖一个引擎为一个项目? – djangofan