shell获取java返回值_java 调用 shell 得到返回值

15、问:

为什么Runtime.exec("ls")没有任何输出?

答:

调用

Runtime.exec方法将产生一个本地的进程,并返回一个Process子类的实例,该实例可用于控制进程或取得进程的相关信息.

由于调用Runtime.exec方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO(如stdin,stdou,stderr)都通过

Process.getOutputStream(),Process.getInputStream(),

Process.getErrorStream()方法重定向给它的父进程了.用户需要用这些stream来向 子进程输入数据或获取子进程的输出.

所以正确执行Runtime.exec("ls")的例程如下:

try

{

process = Runtime.getRuntime().exec (command);

InputStreamReader ir=newInputStreamReader(process.getInputStream());

LineNumberReader input = new LineNumberReader (ir);

String line;

while ((line = input.readLine ()) != null)

System.out.println(line);

}

catch (java.io.IOException e){

System.err.println ("IOException " + e.getMessage());

}

===================================================

例子:import java.io.*;

public class CommandWrapper

{

Process process;

Thread in;

Thread out;

public CommandWrapper(Process process)

{

this.process = process;

final InputStream inputStream

= process.getInputStream();

//final BufferedReader

r=new BufferedReader

(new InputStreamReader(inputStream));

final byte[] buffer = new byte[1024];

out = new Thread()

{

//String line;

int lineNumber=0;

public void run()

{

try {

while (true)

{

int count = inputStream.read(buffer);

System.out.println

(lineNumber+":"+new String

(buffer, 0, count-1));

//line=r.readLine();

//System.out.println

(lineNumber+":"+line);

lineNumber++;

}

}

catch (Exception e)

{

}

}

};

final BufferedReader reader =

new BufferedReader

(new InputStreamReader(System.in));

final OutputStream outputStream

= process.getOutputStream();

in = new Thread()

{

String line;

public void run()

{

try {

while (true)

{

outputStream.write(

(reader.readLine()+"\n").getBytes());

outputStream.flush();

}

}

catch (Exception e)

{

}

}

};

}

public void startIn()

{

in.start();

}

public void startOut()

{

out.start();

}

public void interruptIn()

{

in.interrupt();

}

public void interruptOut()

{

out.interrupt();

}

public static void main(String[] args)

{

try

{

CommandWrapper command =

new CommandWrapper(Runtime.getRuntime().

exec("native2ascii"));

command.startIn();

command.startOut();

}

catch (Exception e) {

e.printStackTrace();

}

}

}

阅读(1098) | 评论(0) | 转发(0) |

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值