- 有时候我们需要在运行
Java
程序时去调用一些shell
脚本或者是python
脚本,Java
提供了一些方式,但是直接使用会存在一些问题,比如传多个参数,或者拿到返回值或者是错误信息等不方便,所以下面写了一个Java
调用命令行的通用方法。
- 因为需要等待调用的脚本完成才能够返回,所以需要进行阻塞,并且为了能够拿到标准输出值或者是错误输出值,需要开启两个线程去获取,否则可能会因为缓冲区满了而出现一些丢失或者其他问题。
代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
public class CmdUtils {
private static final ExecutorService executorService = Executors.newFixedThreadPool(6);
public static Map<String, String> execCmd(String cmd) throws IOException, InterruptedException, ExecutionException {
List<String> cmds = new ArrayList<>();
cmds.add("bash");
cmds.add("-c");
cmds.add(cmd);
ProcessBuilder pb = new ProcessBuilder(cmds);
Process process = pb.start();
Future<String> futureOut = executorService.submit(new ReaTask(process.getInputStream()));
Future<String> futureError = executorService.submit(new ReaTask(process.getErrorStream()));
process.waitFor();
Map<String, String> result = new HashMap<>();
result.put("error", futureError.get());
result.put("out", futureOut.get());
return result;
}
}
class ReaTask implements Callable<String> {
InputStream is;
ReaTask(InputStream is) {
this.is = is;
}
@Override
public String call() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("
");
}
br.close();
return sb.toString();
}