#yyds干货盘点#Process 和 ProcessBuilder

吾生也有涯,而知也无涯。这篇文章主要讲述#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()),重定向到?进程。
【#yyds干货盘点#Process 和 ProcessBuilder】注意:可能会出现标准输?和标准错误输?都有数据,如果对数据的顺序有要求,最简单的做法就是使?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,合并成?个流。





    推荐阅读