#yyds干货盘点#Process 和 ProcessBuilder

Posted 峰啊疯了

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#yyds干货盘点#Process 和 ProcessBuilder相关的知识,希望对你有一定的参考价值。

1、使⽤Runtime

Process process = null;
BufferedReader bufferedReader = null;
String[] command = "/bin/sh", "-c", "cd /home/test & ./test.sh";
try
process = Runtime.getRuntime().exec(command);
bufferedReader = new BufferedReader(new
InputStreamReader(process.getInputStream()));
String line;
while (null != (line = bufferedReader.readLine()))
System.out.println(line);

process.waitFor();
catch (IOException e)
e.printStackTrace();
catch (InterruptedException e)
e.printStackTrace();
finally
if (null != bufferedReader)
try
bufferedReader.close();
catch (IOException e)
e.printStackTrace();


if (null != process)
process.destroy();

Process可以获取到三种流:标准输⼊、标准输出、标准错误输⼊(getOutputStream(),getInputStream(),

getErrorStream()),重定向到⽗进程。

注意:可能会出现标准输⼊和标准错误输⼊都有数据,如果对数据的顺序有要求,最简单的做法就是使⽤ProcessBuilder

合并两个流。

2、使⽤ProcessBuilder

相⽐Process有更多的功能,⽐如可以设置当前⼯作⽬录,还可以改变环境参数

Process process = null;
BufferedReader bufferedReader = null;
String[] command = "/bin/sh", "-c", "cd /home/test & ./test.sh";
try
ProcessBuilder builder = new ProcessBuilder(command);
//合并输⼊流
builder.redirectErrorStream(true);
process = builder.start();
bufferedReader = new BufferedReader(new
InputStreamReader(process.getInputStream()));
String line;
while (null != (line = bufferedReader.readLine())) System.out.println(line);

process.waitFor();
int result = process.exitValue(); //为0表⽰执⾏成功,⾮0表⽰shell执
⾏出错
System.out.println(result);
catch (IOException e)
e.printStackTrace();
catch (InterruptedException e)
e.printStackTrace();
finally
if (null != bufferedReader)
try
bufferedReader.close();
catch (IOException e)
e.printStackTrace();


if (null != process)
process.destroy();

使⽤redirectErrorStream为true,合并成⼀个流。



以上是关于#yyds干货盘点#Process 和 ProcessBuilder的主要内容,如果未能解决你的问题,请参考以下文章

#yyds干货盘点# 进程相关技术原理

#yyds干货盘点#Linux进程

#yyds干货盘点#Linux进程

yum提示Error rpmdb open failed错误的解决#yyds干货盘点#办法

yum提示Error rpmdb open failed错误的解决办法#yyds干货盘点#

#yyds干货盘点#Golang 编码和解析Json