java 命令 返回值_Java调用Linux命令并得到返回值

输出命令调用之后的返回值:

public static void main(String[] args) {

try {

String[] cmd = new String[]{"/bin/sh","-c", "cmd"};

Process ps = Runtime.getRuntime().exec(cmd);

BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));

StringBuffer sb = new StringBuffer();

String line;

while ((line = br.readLine()) != null) {

sb.append(line).append("\n");

}

String result = sb.toString();

System.out.println(result);//输出返回值

} catch (IOException e) {

e.printStackTrace();

}

}

某些程序可能不支持,则需要使用Process.exitValue()来判断程序的运行状态是否成功。

public static void main(String[] args) throws Exception {

try {

String[] cmd = new String[]{"/bin/sh","-c", "cmd"};

Process ps = Runtime.getRuntime().exec(cmd);

ps.waitFor();//阻塞线程,等待数据返回

int i = ps.exitValue();//true is 0 ,false is 1

System.out.println(i);

} catch (IOException e) {

e.printStackTrace();

}

}

如果不使用Process.waitFor()来将线程阻塞,而直接使用Process.exitValue()时,因为exitValue()采用非阻塞的方式返回,如果没有立即拿到返回值,则抛出异常。

Process.waitFor()当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。

当使用Process.waitFor()时可能会导致主线程阻塞,子进程在运行命令时一直没有返回,或者缓冲区已满,需要注意及时清空缓冲区。

在调用waitFor() 的时候,Process需要向主线程汇报运行状况,所以要注意清空缓存区,即InputStream和ErrorStream。

假设该程序不断在向标准输出流和标准错误流写数据,而JVM不读取的话,当缓冲区满之后将无法继续写入数据,最终造成阻塞在waitFor()这里。方法多数是开两个线程在waitFor()命令之前读出窗口的标准输出缓冲区和标准错误流的内容。代码如下:

Runtime rt = Runtime.getRuntime();

String command = "cmd";

try {

p = rt.exec(command ,null,new File("filePath")); //获取进程的标准输入流

final InputStream is1 = p.getInputStream(); //获取进程的错误流

final InputStream is2 = p.getErrorStream(); //启动两个线程,一个线程负责读标准输出流,另一个负责读标准错误流

new Thread() {

public void run() {

BufferedReader br1 = new BufferedReader(new InputStreamReader(is1));

try {

String line1 = null;

while ((line1 = br1.readLine()) != null) {

if (line1 != null){}

}

} catch (IOException e) {

e.printStackTrace();

}

finally{

try {

is1.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}.start();

new Thread() {

public void run() {

BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));

try {

String line2 = null ;

while ((line2 = br2.readLine()) != null ) {

if (line2 != null){}

}

} catch (IOException e) {

e.printStackTrace();

}

finally{

try {

is2.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}.start();

p.waitFor();

p.destroy();

System.out.println("我想被打印...");

} catch (Exception e) {

try{

p.getErrorStream().close();

p.getInputStream().close();

p.getOutputStream().close();

}

catch(Exception ee){}

}

}

Q.E.D.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值