java - 使用 Java 在 Linux 中执行命令并获取输出

标签 java groovy

我正在使用 Groovy 在我的 Linux 机器上执行命令并取回输出,但我无法使用 |以某种方式管道(我认为)或者它可能不等待命令完成。

我的代码有什么问题或遗漏了什么?

我的调用函数:

def test()
{
    String result="N"

    HashMap<String,String> params = IntermediateResults.get("userparams")
    Map env=AppContext.get(AppCtxProperties.environmentVariables)

    def fClass = new GroovyClassLoader().parseClass( new File( 'plugins/infa9/Infa9CommandExecUtil.groovy' ) )
    List<String> frows=["uname -a",
                        "uname -a | awk '{print\$2}'",
                        "uname -a | cut -d ' ' -f 2"]
    List<String> resultRows = fClass.newInstance().fetchCommandOutput( params, env, frows )

    return result
}

Infa9CommandExecUtil.groovy文件内容(更新:添加了 exitVal println):

package infa9

import java.io.BufferedReader;

public class Infa9CommandExecUtil {
  StringBuffer result

  public Infa9CommandExecUtil() {
    result = new StringBuffer()
  }

  public List<String> fetchCommandOutput( Map<String,String> params, Map env, List<String> rows )
  {

        List<String> outputRows = new ArrayList<String>()
        try
        {
            for(item in rows)
            {
                String temp=item.toString()
                println "CMD:$temp"
                Process proc = Runtime.getRuntime().exec(temp);
                InputStream stdin = proc.getInputStream();
                InputStreamReader isr = new InputStreamReader(stdin);
                BufferedReader br = new BufferedReader(isr);
                String line = null;

                result = new StringBuffer()
                line=null

                int exitVal = proc.waitFor()    //do I need to wait for the thread/process to finish here?

                while ((line = br.readLine()) != null)
                {
                    result.append(line+System.getProperty("line.separator"))    //to maintain the format (newlines)
                }
                String tRes=result
                tRes=tRes.trim()
                println "OUTPUT:$tRes\nEXITVAL:$exitVal"

                outputRows.add(tRes)
            }
        }
        catch (IOException io)  {   io.printStackTrace();}
        catch (InterruptedException ie) {ie.printStackTrace();}
    return  outputRows
  }
}

我的输出(更新:添加了 exitVal 值):

CMD:uname -a
OUTPUT:Linux estilo 2.6.18-128.el5 #1 SMP Wed Dec 17 11:41:38 EST 2008 x86_64 x86_64 x86_64 GNU/Linux
EXITVAL:0
CMD:uname -a | awk '{print$2}'
OUTPUT:
EXITVAL:1
CMD:uname -a | cut -d ' ' -f 2
OUTPUT:
EXITVAL:1

注意:我在内部使用 sh -c <command> .

最佳答案

您不能使用 String.execute() 进行管道或重定向。这在 Java 中不起作用,所以它在 Groovy 中也不起作用...

您可以在 Groovy 中使用 Process.pipeTo 来简化事情:

Process proca = 'uname -a'.execute()
Process procb = 'awk {print\$2}'.execute()

(proca | procb).text

更通用的版本可能是:

String process = 'uname -a | awk {print\$2}'

// Split the string into sections based on |
// And pipe the results together
Process result = process.tokenize( '|' ).inject( null ) { p, c ->
  if( p )
    p | c.execute()
  else
    c.execute()
}
// Print out the output and error streams
result.waitForProcessOutput( System.out, System.out )

关于java - 使用 Java 在 Linux 中执行命令并获取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8049854/

相关文章:

java - Java Biginteger 在 pow 中的最大值

java - thymeleaf spring th 属性嵌套循环

java - 在 groovy 中切片字符串

grails - 如何在不使用继承的情况下向 Controller 添加常见操作?

java - 为什么访问说明符不能用于在 Java 类的方法内部声明的变量?

java - 在 Amazon S3 中使用 KMS key 解密文件时出错

java - 错误: Encountered an error executing the step org. springframework.batch.item.ItemStreamException:无法初始化阅读器

grails - Grails 是否使用 isSomethingEnabled() 包围日志语句

java - 将Hibernate 4与Grails 3.2.4结合使用时,启动时会出现NullPointerException

android - 从另一个文件调用 gradle resValue 会导致 "Error:Gradle DSL method not found: ' resValue( )'"