Java执行外部命令 调用Runtime.exec 调用ProcessBuilder

2017-01-02 10:33:00
admin
原创 2104
摘要:Java执行外部命令 调用Runtime.exec 调用ProcessBuilder

一、调用Runtime.exec

exec(String[] cmdarray)
exec(String[] cmdarray, String[] envp)
exec(String[] cmdarray, String[] envp, File dir)
exec(String command)
exec(String command, String[] envp)
exec(String command, String[] envp, File dir)

envp和dir参数说明:

1、不带envp和dir参数的版本实质是传null;

2、envp不为null时,子进程不继承父进程的环境变量;

3、dir不为null时,子进程不继承父进程的工作目录;


代码示例:

public static void exec() throws Exception {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(new String[]{"ls", "mydir"});
InputStream stdout = process.getInputStream();
InputStream stderr = process.getErrorStream();
String line;

InputStreamReader ireader = new InputStreamReader(stdout);
BufferedReader reader = new BufferedReader(ireader);
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

InputStreamReader ireaderErr = new InputStreamReader(stderr);
BufferedReader readerErr = new BufferedReader(ireaderErr);
while ((line = readerErr.readLine()) != null) {
System.out.println(line);
}

process.waitFor();
System.out.println(process.exitValue());
}


二、调用ProcessBuilder(执行外部程序优先使用ProcessBuilder)

ProcessBuilder(List<String> command)
ProcessBuilder(String... command)

environment(),用于修改环境变量;
directory(File directory),用于修改工作目录;

redirect,重定向方法集;

inheritIO(),继承启动进程的输入流、输出流、错误流;

redirectErrorStream(boolean redirectErrorStream),重定向错误流到标准输出流;

start(),启动进程的方法,可重复调用;


ProcessBuilder.Redirect类型:

PIPE,默认重新向类型,使用getInputStream、getErrorStream、getOutputStream进行交互;

INHERIT,inheritIO时设置为此种类型;

READ

WRITE

APPEND


代码示例:

public static void exec2() throws Exception {
ProcessBuilder pb = new ProcessBuilder(new String[]{"ls", "mydir"});
pb.inheritIO();
Process process = pb.start();

process.waitFor();
System.out.println(process.exitValue());
}


三、参数中的空格异常处理

如果单个参数中的空格出现异常,则空格需要进行转义替换。

发表评论
评论通过审核之后才会显示。