背景(可以跳过):
我最近用 Java 编写了一个轻量级服务器,它轮询端口上的新连接,然后当客户端连接时,它会为它们提供自己的线程,直到套接字关闭。现在,一旦客户端连接上,我需要做的是以特殊方式准备 XML 文件请求;如果客户端请求file1.xml,服务器需要读入file1.xml,解析为JSON,并将json对象发送给客户端。
具体问题(现在开始阅读): 我需要用 Java 将 XML 文件解析为 JSON 对象。有人向我推荐 GROOVY 来完成这项任务。在我的 mac 和 ubuntu 分区上安装都很容易,但我无法让内联 groovy 工作,原因很可能是非常微不足道的。这是我现在正在测试的内容(此时,我只是想让嵌入式 groovy 工作):
测试.groovy
output = "Hello ${input}!"
测试.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
我觉得我在编译阶段做错了什么。我怎样才能编译并运行它?
非常感谢帮助
最佳答案
如test.java
是一个 Java 类,而不是 Groovy 脚本,您需要将代码包装在一个类中(重命名为 Test.java
,大写 T
)。您还需要捕获或抛出一些异常:
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException ;
import groovy.util.ScriptException ;
import java.io.IOException ;
public class Test {
public static void main( String[] args ) throws IOException, ResourceException, ScriptException {
String[] roots = new String[] { "." };
GroovyScriptEngine gse = new GroovyScriptEngine(roots);
Binding binding = new Binding();
binding.setVariable("input", "world");
gse.run("test.groovy", binding);
System.out.println(binding.getVariable("output"));
}
}
然后,您需要在类路径上使用 groovy 编译这个 Java 类(使用通配符路径需要 java 6,否则您需要填写 groovy-all-*.jar
的完整路径):
javac -cp $GROOVY_HOME/embeddable/*:. Test.java
并使用正确的类路径运行它:
java -cp $GROOVY_HOME/embeddable/*:. Test
关于java - 基本 Groovy 脚本引擎设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6617396/