How to make System command calls in Java/Groovy?

孤街浪徒 提交于 2019-12-20 09:45:19

问题


What I want to do is invoke maven from a groovy script. The groovy script in question is used as a maven wrapper to build J2EE projects by downloading a tag and invoking maven on what was downloaded. How should I accomplish invoking maven to build/package the EAR (the groovy script is already capable of downloading the tag from SCM).


回答1:


The simplest way to invoke an external process in Groovy is to use the execute() command on a string. For example, to execute maven from a groovy script run this:

"cmd /c mvn".execute()

If you want to capture the output of the command and maybe print it out, you can do this:

print "cmd /c mvn".execute().text

The 'cmd /c' at the start invokes the Windows command shell. Since mvn.bat is a batch script you need this. For Unix you can invoke the system shell.




回答2:


It is as simple as doing

"yourCommand".execute();

If you want to get print outputs on the executed command on standard output you can do

def proc = "yourCommand".execute();
proc.waitForProcessOutput(System.out, System.err);

If you want to store and process the output you can do

def proc = "yourCommand".execute();
def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err);
println(outputStream.toString());

UPDATE:

Also you can set working dir by

File workingDir = file("<path to dir>")
def proc = "yourCommand".execute([], workingDir.absolutePath);



回答3:


For Java 7+ stdio redirection:

new ProcessBuilder('cmd', …args…).redirectOutput(ProcessBuilder.Redirect.INHERIT).start().waitFor();



回答4:


You may use Runtime class to launch a shell command. take a look here: http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#exec(java.lang.String) You may later capture the results of the Process execution (to find out if it failed or not).



来源:https://stackoverflow.com/questions/2701547/how-to-make-system-command-calls-in-java-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!