我们可以使用Runtime.getRuntime().exec("groovy");吗?

3

我安装了Groovy。

enter image description here

我正在尝试使用Java创建的命令提示符来运行Groovy脚本,如下所示:

Runtime.getRuntime().exec("groovy");

如果我在命令行中输入“groovy”,我会得到以下结果:
>>>groovy
Cannot run program "groovy": CreateProcess error=2, The system cannot find the file specified

有人知道出了什么问题吗?我应该使用Groovy的exec实现吗?比如说:
def processBuilder=new ProcessBuilder("ls")
processBuilder.redirectErrorStream(true)
processBuilder.directory(new File("Your Working dir"))  // <--
def process = processBuilder.start()

我猜无论是使用Java实现还是Groovy的实现,都不会有影响。

那么我该如何运行一个groovy脚本呢?


2
你是否将Groovy添加到了你的Path环境变量中? - BlackHatSamurai
2
为什么不直接运行它,这就是它的设计初衷... 点击此处 - Boris the Spider
我重新启动了我的Windows机器,现在它可以工作了。神奇。 - Alexander Mills
1
考虑删除该问题,因为它不可能对任何人有帮助。 - Michael Easter
1
我不知道如何删除一个问题。 - Alexander Mills
显示剩余2条评论
1个回答

2
上述问题中最初描述的调用Groovy可执行文件的方法会调用第二个Java运行时实例和类加载器,而更有效的方法是将Groovy脚本直接嵌入到Java运行时作为Java类并调用它。
以下是从Java执行Groovy脚本的三种方法:
1)最简单的方法是使用GroovyShell
这里是一个示例Java主程序和目标Groovy脚本来调用:
== TestShell.java ==
import groovy.lang.Binding;
import groovy.lang.GroovyShell;

// call groovy expressions from Java code
Binding binding = new Binding();
binding.setVariable("input", "world");
GroovyShell shell = new GroovyShell(binding);
Object retVal = shell.evaluate(new File("hello.groovy"));
// prints "hello world"
System.out.println("x=" + binding.getVariable("x")); // 123
System.out.println("return=" + retVal); // okay

== 你好.groovy ==

println "Hello $input"
x = 123 // script-scoped variables are available via the GroovyShell
return "ok"

2) 接下来使用 GroovyClassLoader 将脚本解析为一个类,然后创建它的实例。这种方法将 Groovy 脚本视为一个类,并像任何 Java 类一样调用其方法。
GroovyClassLoader gcl = new GroovyClassLoader();
Class clazz = gcl.parseClass(new File("hello.groovy");
Object aScript = clazz.newInstance();
// probably cast the object to an interface and invoke methods on it

最后,您可以创建 GroovyScriptEngine并使用绑定传递对象作为变量。这将以脚本方式运行Groovy脚本,并使用绑定变量传递输入,而不是使用带参数的显式方法调用。
注意:此第三个选项适用于想要将Groovy脚本嵌入服务器并在修改时重新加载它们的开发人员。
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;

String[] roots = new String[] { "/my/groovy/script/path" };
GroovyScriptEngine gse = new GroovyScriptEngine(roots);
Binding binding = new Binding();
binding.setVariable("input", "world");
gse.run("hello.groovy", binding);
System.out.println(binding.getVariable("output"));

注意:您必须将 groovy_all jar 包含在 CLASSPATH 中,以使这些方法起作用。
参考:http://groovy.codehaus.org/Embedding+Groovy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接