Java中ProcessBuilder应用实例

系列说明

浅析Java.lang.Runtime类

浅析Java.lang.Process类

浅析Java.lang.ProcessBuilder类

可以使用java中的ProcessBuilder执行本地命令或脚本等工作

以下是一个简单的使用java调用本地python脚本的例子

List<String> commands=new ArrayList();  
commands.add("python");  
commands.add(pkg);  
commands.add("--ad=test");  
//...其它参数添加  
processBuilder.command(commands);  
processBuilder.directory(path);//切换工作目录  
processBuilder.redirectErrorStream(true);  
Process process = processBuilder.start();  
StringBuilder result = new StringBuilder();  
final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));  
try {  
       String line;  
       while ((line = reader.readLine()) != null) {  
           result.append(line);  
           LOGGER.info(processBuilder.command().toString() + " --->: " + line);  
       }  
} catch (IOException e) {  
       LOGGER.warn("failed to read output from process", e);  
} finally {  
       IOUtils.closeQuietly(reader);  
}  
process.waitFor();  
int exit = process.exitValue();  
if (exit != 0) {  
    throw new IOException("failed to execute:" + processBuilder.command() + " with result:" + result);  
} else {  
    return exit;  
}   

更多例子:JDK5.0新特性系列---7.使用ProcessBuilder执行本地命令

你可能感兴趣的:(Java中ProcessBuilder应用实例)