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

我正在使用Groovy在我的

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

我的代码中有什么问题或者我错过了什么?

我的呼叫功能:

def test()

{

String result="N"

HashMap params = IntermediateResults.get("userparams")

Map env=AppContext.get(AppCtxProperties.environmentVariables)

def fClass = new GroovyClassLoader().parseClass( new File( 'plugins/infa9/Infa9CommandExecUtil.groovy' ) )

List frows=["uname -a",

"uname -a | awk '{print\$2}'",

"uname -a | cut -d ' ' -f 2"]

List 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 fetchCommandOutput( Map params, Map env, List rows )

{

List outputRows = new ArrayList()

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>.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值