java ProcessBuilder 执行命令, 读取错误流和标准流消息
public class ExecCommand { public static void main(String[] agrs) throws IOException, InterruptedException { List<String> cmd = new ArrayList<>(); cmd.add("sh"); cmd.add("-c"); cmd.add("ls"); ProcessBuilder pb = new ProcessBuilder(cmd); // 合并 错误流和标准流 pb.redirectErrorStream(true); Process process = pb.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process. getInputStream()))) { if (process.waitFor() != 0) { System.out.println("commond exec error"); } String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 可以使用 org.apache.commons.io 包下的 IoUtils 读流转换为String // IoUtils.tostring(reader); } } }
标签:执行命令,java,String,process,cmd,pb,new From: https://www.cnblogs.com/laizongji/p/16989192.html